/*<br /> * 窩頭類<br /> */<br />class WoTou {<br />int Id;</p><p>WoTou(int Id) {<br />this.Id = Id;<br />}</p><p>public String toString() {<br />return "WoTou " + Id;<br />}<br />}</p><p>/*<br /> * 放窩頭的筐,最多放6個窩頭<br /> */<br />class SyncStack {<br />int index = 0;<br />WoTou[] arrWT = new WoTou[6];</p><p>// 把窩頭放在筐裡<br />public synchronized void Push(WoTou wt) {<br />while (index == arrWT.length) {<br />try{<br />this.wait();<br />}catch(InterruptedException e) {<br />e.printStackTrace();<br />};<br />}<br />this.notify();<br />arrWT[index] = wt;<br />index++;<br />}</p><p>// 從在筐裡拿窩頭<br />public synchronized WoTou Pop() {<br />while (index == 0) {<br />try{<br />this.wait();<br />}catch(InterruptedException e) {<br />e.printStackTrace();<br />};<br />}<br />this.notify();<br />index--;<br />return arrWT[index];<br />}<br />}</p><p>/*<br /> * 生產者<br /> */<br />class Producer implements Runnable {<br />SyncStack ss = null;</p><p>Producer(SyncStack ss) {<br />this.ss = ss;<br />}</p><p>@Override<br />public void run() {<br />for (int i = 0; i < 20; i++) {<br />WoTou wt = new WoTou(i);<br />ss.Push(wt);<br />System.out.println("生產了:" + wt);<br />try{<br />Thread.sleep((int)(Math.random() * 200));<br />}catch(InterruptedException e) {<br />e.printStackTrace();<br />};<br />}<br />}<br />}</p><p>/*<br /> * 消費者<br /> */<br />class Consumer implements Runnable {<br />SyncStack ss = null;</p><p>Consumer(SyncStack ss) {<br />this.ss = ss;<br />}</p><p>@Override<br />public void run() {<br />for (int i = 0; i < 20; i++) {<br />WoTou wt = ss.Pop();<br />System.out.println("消費了:" + wt);<br />try{<br />Thread.sleep((int)(Math.random() * 1000));<br />}catch(InterruptedException e) {<br />e.printStackTrace();<br />};<br />}<br />}<br />}</p><p>/*<br /> * 測試類別<br /> */<br />public class Test {<br />public static void main(String[] args) {<br />SyncStack ss = new SyncStack();<br />Producer p = new Producer(ss);<br />Consumer c = new Consumer(ss);<br />new Thread(p).start();<br />new Thread(c).start();<br />}</p><p>}
一個生產者一個消費者,並且生產的窩頭全部消費掉。
如果是多個生產者,多個消費時,使用notifyAll()代替notify();