例子如下:
package com.dx.juc.test; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class LockAndConditionTest { public static void main(String[] args) { Clerk clerk = new Clerk(); Productor productor = new Productor(clerk); Consumer consumer = new Consumer(clerk); new Thread(productor, "Productor-A").start(); new Thread(consumer, "Consumer-A").start(); new Thread(productor, "Productor-B").start(); new Thread(consumer, "Consumer-B").start(); } } /** * 店员 */ class Clerk { private int product = 0; private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); /** * 进货 */ public void purchase() { lock.lock(); try { while (product >= 1) { System.out.println(Thread.currentThread().getName() + ":" + "产品已满。。。"); try { condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + ":" + ++product); condition.signalAll(); } finally { lock.unlock(); } } /** * 卖货 */ public void sell() { lock.lock(); try { while (product <= 0) { System.out.println(Thread.currentThread().getName() + ":" + "产品缺貨。。。"); try { condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + ":" + --product); condition.signalAll(); } finally { lock.unlock(); } } } /** * 生产者 不断的生产产品给店员 */ class Productor implements Runnable { private Clerk clerk; public Productor(Clerk clerk) { this.clerk = clerk; } public void run() { for (int i = 0; i < 2; i++) { clerk.purchase(); } } } /** * 消费者 不断的从店员那里消费产品 */ class Consumer implements Runnable { private Clerk clerk; public Consumer(Clerk clerk) { this.clerk = clerk; } public void run() { for (int i = 0; i < 2; i++) { clerk.sell(); } } }
原文:https://www.cnblogs.com/yy3b2007com/p/8972263.html