package 多线程; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class PandCnewLock { public static void main(String[] args) { // Producer p= new Producer2(); // Consumer c = new Consumer2(); // new Thread(p,"生产者").start(); // new Thread(p,"生产者").start(); // new Thread(c,"消费者").start(); // new Thread(c,"消费者").start(); new Thread(new Producer2(),"生产者").start(); new Thread(new Consumer2(),"消费者").start(); new Thread(new Producer2(),"生产者").start(); new Thread(new Consumer2(),"消费者").start(); } } class Producer2 implements Runnable{ Resource2 r = Resource2.getRes(); @Override public void run() { while(true) r.produce("商品:"); } } class Consumer2 implements Runnable{ Resource2 r = Resource2.getRes(); @Override public void run() { while(true) r.consume(); } } class Resource2{ private int count; private boolean flag=false; static Resource2 r = new Resource2(); Lock lock = new ReentrantLock(); Condition cp = lock.newCondition(); Condition cc = lock.newCondition(); private Resource2() { } public static Resource2 getRes(){ return r; } public void produce(String name){ lock.lock();//上锁 try { while(!flag) try { cp.await(); //与此 Condition 相关的锁以原子方式释放,并且出于线程调度的目的,将禁用当前线程, } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } name = name+count++; flag=false; System.out.println(Thread.currentThread().getName()+" .........生产商品:"+count); cc.signal();//唤醒一个cc上等待线程。 } finally { lock.unlock(); } } public void consume(){ lock.lock(); try { while(flag) try { cc.await(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } flag=true; System.out.println(Thread.currentThread().getName()+" ======消费商品:"+count); cp.signal(); } finally { lock.unlock(); } } }
本文出自 “要么拼命,要么滚回去!” 博客,请务必保留此出处http://jiangzuun2014.blog.51cto.com/8732469/1441287