线程介绍,异步,对象锁

Java多线程编程总结

线程基础:

当创建线程时,会为非static对象各自申请内存空间

卖票程序:

线程的优先级用1-10之间的整数表示,数值越大优先级越高,默认的优先级为5。

pupublic class Main {
 static int ticket = 10;
 static Runnable mRunnable = new Runnable() {
  @Override
  public void run() {
   // TODO Auto-generated method stub
   while (true) {
    synchronized (this) {
     if (ticket > 0) {
      try {
       Thread.sleep(1000);
       System.out.println(Thread.currentThread().getName()
         + "卖出票-->" + ticket--);
      } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
     } else {
      break;
     }
    }
   }
  }
 };
 public static void main(String[] args) {
  Thread t1 = new Thread(mRunnable, "线程, A\t");
  Thread t2 = new Thread(mRunnable, "线程, B\t");
  t1.setPriority(1);
  t2.setPriority(10);
  t1.start();
  t2.start();
 }
}

 卖票程序(两线程各自有自己的票仓库)

将ticket设为non-static

public class MyThread implements Runnable {
 int ticket = 100;
 @Override
 public void run() {
  // TODO Auto-generated method stub
  while (true) {
   synchronized (this) {
    if (ticket > 0) {
     try {
      Thread.sleep(10);
      System.out.println(Thread.currentThread().getName() + "卖出票-->" + ticket--);
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    } else {
     break;
    }
   }
  }
 }
 public static void main(String[] args) {
  Runnable run1 = new MyThread();
  Runnable run2 = new MyThread();
  Thread t1 = new Thread(run1,"线程   A\t");
  Thread t2 = new Thread(run2,"线程   B\t");
  t1.start();
  t2.start();
  try {
   t1.join(); 
   System.out.println(t1.getName() + "卖完票");
   t2.join();
   System.out.println(t2.getName() + "卖完票");
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

 

一个死锁案例:Java:多线程死锁

public class LockDemo implements Runnable{
 private static Object object1 = new Object();
    
    private static Object object2 = new Object();
     
    private int flag = 0;
 public static void main(String[] args) throws InterruptedException {
  LockDemo run0 = new LockDemo();
  LockDemo run1 = new LockDemo();    
        run0.flag = 1;    //here    
        run1.flag = 2;    //
        Thread thread1 = new Thread(run0);
        Thread thread2 = new Thread(run1);
        thread1.start();
        thread2.start();
    }
     
    @Override
    public void run()
    {
        System.out.println(flag);
        if (flag == 1)
        {
            synchronized (object1)
            {
                System.out.println("线程 : " + flag + "锁定obj1,休息0.5秒后锁定obj2去!");
                try
                {
                    Thread.sleep(500);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                synchronized (object2)
                {
                    System.out.println("线程 : " + flag + "访问 object2");
                }
            }
        }
        if (flag == 2)
        {
            synchronized (object2)
            {
                System.out.println("线程 : " + flag + "锁定obj2,休息0.5秒后锁定obj1去!");
                try
                {
                    Thread.sleep(500);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                synchronized (object1)
                {
                    System.out.println("线程 : " + flag + "访问object1");
                }
            }
        }
         
    }
}

结果:

2

线程 : 2锁定obj2,休息0.5秒后锁定obj1去!

1

线程 : 1锁定obj1,休息0.5秒后锁定obj2去!

 

对象锁、notifyAll、notify、wait

wait()方法 
在其他线程调用对象的notify或notifyAll方法前,导致当前线程等待。线程会释放掉它所占有的“锁标志”,从而使别的线程有机会抢占该锁。 
唤醒当前对象锁的等待线程使用notify或notifyAll方法,wait() 和notify()必须在synchronized函数或synchronized block中进行调用。

Calculator.java:

//计算线程  
public class Calculator extends Thread {
 private int total;
 public int getTotal() {
  return total;
 }
 public void run() {
  synchronized (this) {
   for (int i = 0; i < 10; i++) {
    total += i;
   }
   // 通知所有在此对象上等待的线程
   notifyAll();
  }
 }
}

ReaderResult.java:

public class ReaderResult extends Thread {
 Calculator c;
 public ReaderResult(Calculator c) {
  this.c = c;
 }
 public void run() {
  synchronized (c) {
   try {
    System.out.println(Thread.currentThread() + "等待计算结果。。。");
    c.wait();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   System.out
     .println(Thread.currentThread() + "计算结果为:" + c.getTotal());
  }
 }
 public static void main(String[] args) {
  // 启动5个线程,分别获取计算结果
  Calculator calculator = new Calculator();
  for (int i = 0; i < 5; i++) {
   new ReaderResult(calculator).start();
  }
  // 启动计算线程
  calculator.start();
 }
}

结果:

Thread[Thread-1,5,main]等待计算结果。。。

Thread[Thread-2,5,main]等待计算结果。。。

Thread[Thread-3,5,main]等待计算结果。。。

Thread[Thread-5,5,main]等待计算结果。。。

Thread[Thread-4,5,main]等待计算结果。。。

Thread[Thread-1,5,main]计算结果为:45

Thread[Thread-4,5,main]计算结果为:45

Thread[Thread-5,5,main]计算结果为:45

Thread[Thread-3,5,main]计算结果为:45

Thread[Thread-2,5,main]计算结果为:45

 

 线程jion方法:等待该线程终止。等待调用join方法的线程结束,再继续执行。

public class Main {
 static class MyThread implements Runnable {
  @Override
  public void run() {
   // TODO Auto-generated method stub
   for (int i = 0; i < 5; i++) {
    try {
     Thread.sleep(1000);
     show("XIXI RUN->slower and slower");
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
 }
 public static void main(String args[]) {
  Runnable mRunnable = new MyThread();
  Thread t1 = new Thread(mRunnable, "xixi");
  t1.start();
  try {
   t1.join();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  show("MAIN RUN->CAN YOU BE FAST");
 }
 private static void show(String str) {
  System.out.println(str);
 }
}

结果:

XIXI RUN->slower and slower

XIXI RUN->slower and slower

XIXI RUN->slower and slower

XIXI RUN->slower and slower

XIXI RUN->slower and slower

MAIN RUN->CAN YOU BE FAST

你可能感兴趣的:(线程介绍,异步,对象锁)