首页 > 代码库 > 多线程——生产者与消费者(多)1.5新锁,问题解决
多线程——生产者与消费者(多)1.5新锁,问题解决
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
多线程——生产者与消费者(多)1.5新锁,问题解决
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。