標籤:
import java.util.concurrent.locks.*; class Do9 { public static void main(String[] args) { Resource r=new Resource(); Shengchan sc=new Shengchan(r); Xiaoshou xs=new Xiaoshou(r); Thread th1=new Thread(sc); Thread th2=new Thread(sc); Thread th3=new Thread(xs); Thread th4=new Thread(xs); th1.start(); th2.start(); th3.start(); th4.start(); }}class Resource{ private String name; private int count=1; private boolean flag=false; //建立一個鎖對像 Lock lock=new ReentrantLock(); //通過已經有的鎖擷取該鎖上的監視器對象 Condition shengchan_con=lock.newCondition();//建立生產者對象 Condition xiaofei_con=lock.newCondition();//建立消費者對象 public void set(String name) { lock.lock(); try { while(flag) try{shengchan_con.await();}catch(InterruptedException e){} this.name=name+count; count++; System.out.println(Thread.currentThread().getName()+"..生產者.."+this.name); flag=true; xiaofei_con.signal(); } finally{ lock.unlock(); } } public synchronized void out() { lock.lock(); try { while(!flag) try{xiaofei_con.await();}catch(InterruptedException e){} System.out.println(Thread.currentThread().getName()+"..消費者........"+this.name); flag=false; shengchan_con.signal(); } finally{ lock.unlock(); } }}class Shengchan implements Runnable{ private Resource r; Shengchan(Resource r) { this.r=r; } public void run() { while(true) { try{Thread.sleep(150);}catch(InterruptedException e){} r.set("烤鴨"); } }}class Xiaoshou implements Runnable{ private Resource r; Xiaoshou(Resource r) { this.r=r; } public void run() { while(true) { try{Thread.sleep(150);}catch(InterruptedException e){} r.out(); } }}
java新版中喚醒指定線層對象