03.线程的通知与等待

public class NotifyAllDemo {
    private static volatile Object reA = new Object();
   public static void main(String[] args) throws InterruptedException{
       Thread threadA = new Thread(new Runnable() {
           @Override
           public void run() {
               synchronized (reA){
                   System.out.println("threadA get reA lock");
                   try {
                       System.out.println("threadA begin wait");
                       reA.wait();
                       System.out.println("threadA end wait");
                   }catch (InterruptedException e){
                       e.printStackTrace();
                   }
               }
           }
       });
       Thread threadB = new Thread(new Runnable() {
           @Override
           public void run() {
               synchronized (reA){
                   System.out.println("threadB get reA lock");
                   try {
                       System.out.println("threadB begin wait");
                       reA.wait();
                       System.out.println("threadB end wait");
                   }catch (InterruptedException e){
                       e.printStackTrace();
                   }
               }
           }
       });
       Thread threadC = new Thread(new Runnable() {
           @Override
           public void run() {
               synchronized (reA){
                   System.out.println("threadC begin notify");
                   //reA.notify();
                   reA.notifyAll();
               }
           }
       });
       threadA.start();
       threadB.start();
       Thread.sleep(1000);
       threadC.start();
       threadA.join();
       threadB.join();
       threadC.join();
       System.out.println("main over");

       //调用notify()
       //threadA get reA lock
       //threadA begin wait
       //threadB get reA lock
       //threadB begin wait
       //threadC begin notify
       //threadA end wait

       //调用notifyAll()
       //threadA get reA lock
       //threadA begin wait
       //threadB get reA lock
       //threadB begin wait
       //threadC begin notify
       //threadA end wait
       //threadB end wait
       //main over
       
       //在线程 B 调用共享变量的 wait()方法前线程C调用了共享变量的 notifyAll 方法, 这样,只有线程 A 被唤醒,而线程 B 并没有被唤醒, 还是处于阻塞状态
   }
}

猜你喜欢

转载自www.cnblogs.com/fly-book/p/11361616.html
03.