package thread.lock; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /* * 生产消费问题 */ class Resource{ private String name; private int count = 1; private boolean flag = false; //一个锁 Lock lock = new ReentrantLock(); //获取两组监视器 Condition pro_lock = lock.newCondition(); Condition con_lock = lock.newCondition(); public void set(String name){ lock.lock(); try { while (flag) try { pro_lock.await(); } catch (InterruptedException e) { e.printStackTrace(); } this.name = name + count; System.out.println(Thread.currentThread().getName()+".pro."+this.name); count++; flag = true; con_lock.signal(); } finally { lock.unlock(); } } public void out(){ lock.lock(); try{ while(!flag) try { con_lock.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"...con..."+this.name); flag = false; pro_lock.signal(); } finally { lock.unlock(); } } } class Producer implements Runnable{ private Resource r; public Producer(Resource r) { this.r = r; } @Override public void run() { while(true) r.set("chicken"); } } class Consumer implements Runnable{ private Resource r; public Consumer(Resource r) { this.r = r; } @Override public void run() { while(true) r.out(); } } public class ProducerConsumerDemo { public static void main(String[] args) { Resource r = new Resource(); Producer p = new Producer(r); Consumer c = new Consumer(r); Thread t0 = new Thread(p); Thread t1 = new Thread(p); Thread t2 = new Thread(c); Thread t3 = new Thread(c); t0.start(); t1.start(); t2.start(); t3.start(); } }