模式5-Producer-Consumer
参考《java多线程设计模式》
在多个生产者和多个消费者之间加入一个中间者来缓冲线程之间的处理速度差。
// 放置蛋糕 public synchronized void put(String cake) throws InterruptedException { System.out.println(Thread.currentThread().getName() + " puts " + cake); while (count >= buffer.length) { wait(); } buffer[tail] = cake; tail = (tail + 1) % buffer.length; count++; notifyAll(); } // 取得蛋糕 public synchronized String take() throws InterruptedException { while (count <= 0) { wait(); } String cake = buffer[head]; head = (head + 1) % buffer.length; count--; notifyAll(); System.out.println(Thread.currentThread().getName() + " takes " + cake); return cake; }
浙公网安备 33010602011771号