一個鎖多個執行緒監視器(jdk1.5新特性)
阿新 • • 發佈:2019-01-04
import java.util.concurrent.locks.*;//匯入Renntrantlock的包 class Resource { private String name; private int count = 1; private boolean flag = false; // 建立一個鎖物件。 Lock lock = new ReentrantLock(); //通過已有的鎖獲取該鎖上的監視器物件。 // Condition con = lock.newCondition(); //通過已有的鎖獲取兩組監視器,一組監視生產者,一組監視消費者。 Condition producer_con = lock.newCondition(); Condition consumer_con = lock.newCondition(); public void set(String name)// t0 t1 { lock.lock(); try { while(flag) // try{lock.wait();}catch(InterruptedException e){}// t1 t0 try{producer_con.await();}catch(InterruptedException e){}// t1 t0 this.name = name + count;//烤鴨1 烤鴨2 烤鴨3 count++;//2 3 4 System.out.println(Thread.currentThread().getName()+"...生產者5.0..."+this.name);//生產烤鴨1 生產烤鴨2 生產烤鴨3 flag = true; // notifyAll(); // con.signalAll(); consumer_con.signal();//當生產者的一個執行緒結束,喚醒消費者的任一個執行緒 } finally { lock.unlock(); } } public void out()// t2 t3 { lock.lock(); try { while(!flag) // try{this.wait();}catch(InterruptedException e){} //t2 t3 try{cousumer_con.await();}catch(InterruptedException e){} //t2 t3 System.out.println(Thread.currentThread().getName()+"...消費者.5.0......."+this.name);//消費烤鴨1 flag = false; // notifyAll(); // con.signalAll(); producer_con.signal();//當消費者的一個執行緒結束,喚醒生產者的任一個執行緒 } finally { lock.unlock(); } } } class Producer implements Runnable { private Resource r; Producer(Resource r) { this.r = r; } public void run() { while(true) { r.set("烤鴨"); } } } class Consumer implements Runnable { private Resource r; Consumer(Resource r) { this.r = r; } public void run() { while(true) { r.out(); } } } class ProducerConsumerDemo2 { public static void main(String[] args) { Resource r = new Resource(); Producer pro = new Producer(r); Consumer con = new Consumer(r); Thread t0 = new Thread(pro); Thread t1 = new Thread(pro); Thread t2 = new Thread(con); Thread t3 = new Thread(con); t0.start(); t1.start(); t2.start(); t3.start(); } }