# 代码:
public class App { public static void main(String[] args) { Depot depot = new Depot(100); Producer producer = new Producer(depot); Consumer consumer = new Consumer(depot); producer.produce(60); consumer.consume(100); producer.produce(90); consumer.consume(40); } } class Producer { private Depot depot; public Producer(Depot depot) { this.depot = depot; } public void produce(final int val) { new Thread() { public void run() { depot.produce(val); } }.start(); } } class Consumer { private Depot depot; public Consumer(Depot depot) { this.depot = depot; } public void consume(final int val) { new Thread() { public void run() { depot.consume(val); } }.start(); } } class Depot { private int capacity; private int size; private Lock lock; private Condition fullCondition; private Condition emptyCondition; public Depot(int capacity) { this.size = 0; this.capacity = capacity; this.lock = new ReentrantLock(); fullCondition = lock.newCondition(); emptyCondition = lock.newCondition(); } public void produce(int val) { lock.lock(); try { int surplus = val; while (surplus > 0) { while (size >= capacity) { fullCondition.await(); } int incre = (size + surplus) > capacity ? (capacity - size) : surplus; size += incre; surplus -= incre; System.out.printf("%s plan to produce (%d), actually produce (%d), depot size (%d) \n", Thread.currentThread().getName(), val, incre, size); emptyCondition.signal(); } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void consume(int val) { lock.lock(); try { int surplus = val; while (surplus > 0) { while (size <= 0) { emptyCondition.await(); } int desc = (size < surplus) ? size : surplus; size -= desc; surplus -= desc; System.out.printf("%s plan to consume (%d), actutally consume (%d), depot size (%d) \n", Thread.currentThread().getName(), val, desc, size); fullCondition.signalAll(); } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } }
# 输出:
Thread-0 plan to produce (60), actually produce (60), depot size (60)
Thread-1 plan to consume (100), actutally consume (60), depot size (0)
Thread-2 plan to produce (90), actually produce (90), depot size (90)
Thread-3 plan to consume (40), actutally consume (40), depot size (50)
Thread-1 plan to consume (100), actutally consume (40), depot size (10)