/*
下面的程序会出现下面的情况,当Thread-0, Thread-1, Thread-2都被wait的时候,可能会同时苏醒
Thread-0 put
Thread-1 put
Thread-2 put
Thread-3 get//在此处,Thread-3拿到锁之后,将所有的等待的线程唤醒,才有了下面的输出
Thread-2 put
Thread-1 put
Thread-0 put
*/
虽然多个线程会同时苏醒,但是只有一个能获得cpu的执行权!
总之,同步中执行的只能是一个,但是存活的不一定就是一个!
class DuckD{
public void put(){
synchronized(DuckD.class){
System.out.println(Thread.currentThread().getName()+" put");
try{
DuckD.class.wait();//Thread-0, Thread-1, Thread-2可能会同时在这里苏醒!
}catch(InterruptedException e){
}
//........
}
}
public void get(){
synchronized(DuckD.class){
DuckD.class.notifyAll();
System.out.println(Thread.currentThread().getName()+" get");
try{
DuckD.class.wait();
}catch(InterruptedException e){
}
}
}
}
class ProduceD implements Runnable{
DuckD dk;
ProduceD(DuckD dk){
this.dk=dk;
}
public void run(){
while(true)
dk.put();
}
}
class ConsumeD implements Runnable{
DuckD dk;
ConsumeD(DuckD dk){
this.dk=dk;
}
public void run(){
while(true)
dk.get();
}
}
class Test{
public static void main(String[] args){
DuckD dk=new DuckD();
Thread t1=new Thread(new ProduceD(dk));
Thread t2=new Thread(new ProduceD(dk));
Thread t3=new Thread(new ProduceD(dk));
Thread t4=new Thread(new ConsumeD(dk));
t1.start();
t2.start();
t3.start();
t4.start();
}
}