多生产-多消费

import java.util.concurrent.locks.*; // 1.5版本lock代替synchronized
//
资源 class Resource { // 首先私有数据,不直接对外暴露,只提供方法 private String name; // 烤鸭name private int count = 1; // 烤鸭编号 private boolean flag = false;
// lock 互斥锁替代同步,当前lock运行,别的lock无法运行
Lock lock = new ReentrantLock();
// 获取该lock的监视器,可随意获取多个独立监视器用于特定需求,替代Object的wait notify notifyAll方法
Condition producer_con = lock.newCondition();
  Condition consumer_con = lock.newCondition();
  public void newSet(String name) {
lock.lock();
try {
// while...con.await 唤醒对方signal,不用All signalAll
}
finally {
lock.unlock();
}
}
// 生产与消费之间的线程需要等待唤醒,采用同步函数或同步代码块 public synchronized void set(String name) { while(flag) // 唤醒下面wait后的线程,每次都要再 try 一下判断flag try{this.wait();}catch(InterruptedException e){} // wait 方法需要声明或捕捉异常 this.name = name + count; count++; Sop(Thread.cuuentThread().getName()+"...生产者..."+this.name); flag = true; notifyAll(); // 全唤醒避免死锁,由于flag必定唤醒对方线程 } public synchronized void out() { while(!flag) try{this.wait();}catch(InterruptedException e){} Sop(Thread.cuuentThread().getName()+"...消费者..."+this.name); flag = false; notifyAll(); } } 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 { 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(); } }

 

posted @ 2019-12-03 10:30  blackatall  阅读(94)  评论(0)    收藏  举报