多線程的生產者消費執行個體

來源:互聯網
上載者:User
/*<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();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.