Condition线程通信_生产者消费者案例
①Condition 接口描述了可能会与锁有关联的条件变量。
这些变量在用 法上与使用 Object.wait 访问的隐式监视器类似,但提供了更强大的 功能。
需要特别指出的是,单个 Lock 可能与多个 Condition 对象关 联。
为了避免兼容性问题,Condition 方法的名称与对应的 Object 版 本中的不同。
② 在 Condition 对象中,与 wait、notify 和 notifyAll 方法对应的分别是 await、signal 和 signalAll。
③ Condition 实例实质上被绑定到一个锁上。要为特定 Lock 实例获得 Condition 实例,请使用其 newCondition() 方法
TestProductorAndConsumer1
package com.aff.juc; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; //生产者消费者案例,Lock public class TestProductorAndConsumer1 { public static void main(String[] args) { Clerk1 clerk1 = new Clerk1(); Productor1 pro = new Productor1(clerk1); Consumer1 cus = new Consumer1(clerk1); new Thread(pro, "生产者A").start(); new Thread(cus, "消费者B").start(); new Thread(pro, "生产者C").start(); new Thread(cus, "消费者D").start(); } } // 店员 class Clerk1 { private int product = 0; private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); // 进货 public void get() { lock.lock();// 上锁 try { while (product >= 1) { // 为了避免虚假唤醒问题,应该总是使用在循环中 System.out.println("产品已满"); try { condition.await(); } catch (InterruptedException e) { } } System.out.println(Thread.currentThread().getName() + ":" + ++product); condition.signalAll(); }finally { lock.unlock(); } } // 卖货 public void sale() { lock.lock(); try { while (product <= 0) { System.out.println("缺货"); try { condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + ":" + --product); condition.signalAll(); } finally { lock.unlock(); } } } // 生产者 class Productor1 implements Runnable { private Clerk1 clerk1; public Productor1(Clerk1 clerk) { this.clerk1 = clerk; } @Override public void run() { for (int i = 0; i < 20; i++) { try { Thread.sleep(200); } catch (Exception e) { } clerk1.get(); } } } // 消费者 class Consumer1 implements Runnable { private Clerk1 clerk1; public Consumer1(Clerk1 clerk) { this.clerk1= clerk; } @Override public void run() { for (int i = 0; i < 20; i++) { clerk1.sale(); } } }
All that work will definitely pay off