1 /* 2 下面的程序會出現下面的情況,當Thread-0, Thread-1, Thread-2都被wait的時候,可能會同時蘇醒 3 Thread-0 put 4 Thread-1 put 5 Thread-2 put 6 Thread-3 get//在此處,Thread-3拿到鎖之后,將所有的等待的線程喚醒,才有了下面的輸出 7 Thread-2 put 8 Thread-1 put 9 Thread-0 put 10 */ 11 12 13 雖然多個線程會同時蘇醒,但是只有一個能獲得cpu的執行權! 14 總之,同步中執行的只能是一個,但是存活的不一定就是一個! 15 16 17 class DuckD{ 18 public void put(){ 19 20 synchronized(DuckD.class){ 21 22 System.out.println(Thread.currentThread().getName()+" put"); 23 try{ 24 DuckD.class.wait();//Thread-0, Thread-1, Thread-2可能會同時在這里蘇醒! 25 }catch(InterruptedException e){ 26 27 } 28 //........ 29 } 30 } 31 32 public void get(){ 33 34 synchronized(DuckD.class){ 35 36 DuckD.class.notifyAll(); 37 System.out.println(Thread.currentThread().getName()+" get"); 38 try{ 39 DuckD.class.wait(); 40 }catch(InterruptedException e){ 41 42 } 43 } 44 } 45 } 46 47 class ProduceD implements Runnable{ 48 DuckD dk; 49 ProduceD(DuckD dk){ 50 this.dk=dk; 51 } 52 public void run(){ 53 while(true) 54 dk.put(); 55 } 56 } 57 58 class ConsumeD implements Runnable{ 59 DuckD dk; 60 ConsumeD(DuckD dk){ 61 this.dk=dk; 62 } 63 public void run(){ 64 while(true) 65 dk.get(); 66 } 67 } 68 69 class Test{ 70 public static void main(String[] args){ 71 DuckD dk=new DuckD(); 72 Thread t1=new Thread(new ProduceD(dk)); 73 Thread t2=new Thread(new ProduceD(dk)); 74 Thread t3=new Thread(new ProduceD(dk)); 75 Thread t4=new Thread(new ConsumeD(dk)); 76 77 t1.start(); 78 t2.start(); 79 t3.start(); 80 t4.start(); 81 } 82 }
?