Java多線程之並發協作生產者消費者設計模式

來源:互聯網
上載者:User

標籤:同步機制   通過   產品   rgs   www   bsp   java   停止   消費者   

兩個線程一個生產者個一個消費者

需求情景

  • 兩個線程,一個負責生產,一個負責消費,生產者生產一個,消費者消費一個

涉及問題

  • 同步問題:如何保證同一資源被多個線程並發訪問時的完整性。常用的同步方法是採用標記或加鎖機制
  • wait() / nofity() 方法是基類Object的兩個方法,也就意味著所有Java類都會擁有這兩個方法,這樣,我們就可以為任何對象實現同步機制。
  • wait()方法:當緩衝區已滿/空時,生產者/消費者線程停止自己的執行,放棄鎖,使自己處於等等狀態,讓其他線程執行。
  • notify()方法:當生產者/消費者向緩衝區放入/取出一個產品時,向其他等待的線程發出可執行檔通知,同時放棄鎖,使自己處於等待狀態。

代碼實現(共三個類和一個main方法的測試類別)

Resource.java

/** * Created by yuandl on 2016-10-11./** * 資源 */public class Resource {    /*資源序號*/    private int number = 0;    /*資源標記*/    private boolean flag = false;    /**     * 生產資源     */    public synchronized void create() {        if (flag) {//先判斷標記是否已經生產了,如果已經生產,等待消費;            try {                wait();//讓生產線程等待            } catch (InterruptedException e) {                e.printStackTrace();            }        }        number++;//生產一個        System.out.println(Thread.currentThread().getName() + "生產者------------" + number);        flag = true;//將資源標記為已經生產        notify();//喚醒在等待操作資源的線程(隊列)    }    /**     * 消費資源     */    public synchronized void destroy() {        if (!flag) {            try {                wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        System.out.println(Thread.currentThread().getName() + "消費者****" + number);        flag = false;        notify();    }}

Producer.java

/** * Created by yuandl on 2016-10-11. * /** * 生產者   http://www.manongjc.com */public class Producer implements Runnable {    private Resource resource;    public Producer(Resource resource) {        this.resource = resource;    }    @Override    public void run() {        while (true) {            try {                Thread.sleep(10);            } catch (InterruptedException e) {                e.printStackTrace();            }            resource.create();        }    }}

Consumer.java

/** * 消費者 */public class Consumer implements Runnable {    private Resource resource;    public Consumer(Resource resource) {        this.resource = resource;    }    @Override    public void run() {        while (true) {            try {                Thread.sleep(10);            } catch (InterruptedException e) {                e.printStackTrace();            }            resource.destroy();        }    }}

ProducerConsumerTest.java

/** * Created by yuandl on 2016-10-11. */public class ProducerConsumerTest {    public static void main(String args[]) {        Resource resource = new Resource();        new Thread(new Producer(resource)).start();//生產者線程        new Thread(new Consumer(resource)).start();//消費者線程    }}

列印結果:

Thread-0生產者------------1Thread-1消費者****1Thread-0生產者------------2Thread-1消費者****2Thread-0生產者------------3Thread-1消費者****3Thread-0生產者------------4Thread-1消費者****4Thread-0生產者------------5Thread-1消費者****5Thread-0生產者------------6Thread-1消費者****6Thread-0生產者------------7Thread-1消費者****7Thread-0生產者------------8Thread-1消費者****8Thread-0生產者------------9Thread-1消費者****9Thread-0生產者------------10Thread-1消費者****10

以上列印結果可以看出沒有任何問題

 

多個線程,多個生產者和多個消費者的問題

需求情景

  • 四個線程,兩個個負責生產,兩個個負責消費,生產者生產一個,消費者消費一個

涉及問題

  • notifyAll()方法:當生產者/消費者向緩衝區放入/取出一個產品時,向其他等待的所有線程發出可執行檔通知,同時放棄鎖,使自己處於等待狀態。

再次測試代碼

ProducerConsumerTest.java

** * Created by yuandl on 2016-10-11. */public class ProducerConsumerTest {    public static void main(String args[]) {        Resource resource = new Resource();        new Thread(new Consumer(resource)).start();//生產者線程        new Thread(new Consumer(resource)).start();//生產者線程        new Thread(new Producer(resource)).start();//消費者線程        new Thread(new Producer(resource)).start();//消費者線程    }}

運行結果:

Thread-0生產者------------100Thread-3消費者****100Thread-0生產者------------101Thread-3消費者****101Thread-2消費者****101Thread-1生產者------------102Thread-3消費者****102Thread-0生產者------------103Thread-2消費者****103Thread-1生產者------------104Thread-3消費者****104Thread-1生產者------------105Thread-0生產者------------106Thread-2消費者****106Thread-1生產者------------107Thread-3消費者****107Thread-0生產者------------108Thread-2消費者****108Thread-0生產者------------109Thread-2消費者****109Thread-1生產者------------110Thread-3消費者****110

通過以上列印結果發現問題

  • 101生產了一次,消費了兩次
  • 105生產了,而沒有消費

原因分析

  • 當兩個線程同時操作生產者生產或者消費者消費時,如果有生產者或者的兩個線程都wait()時,再次notify(),由於其中一個線程已經改變了標記而另外一個線程再次往下直接執行的時候沒有判斷標記而導致的。
  • if判斷標記,只有一次,會導致不該啟動並執行線程運行了。出現了資料錯誤的情況。

解決方案

  • while判斷標記,解決了線程擷取執行權後,是否要運行!也就是每次wait()後再notify()時先再次判斷標記

 

代碼改進(Resource中的if->while) 

Resource.java

/** * Created by yuandl on 2016-10-11./** * 資源 */public class Resource {    /*資源序號*/    private int number = 0;    /*資源標記*/    private boolean flag = false;    /**     * 生產資源     */    public synchronized void create() {        while (flag) {//先判斷標記是否已經生產了,如果已經生產,等待消費;            try {                wait();//讓生產線程等待            } catch (InterruptedException e) {                e.printStackTrace();            }        }        number++;//生產一個        System.out.println(Thread.currentThread().getName() + "生產者------------" + number);        flag = true;//將資源標記為已經生產        notify();//喚醒在等待操作資源的線程(隊列)    }    /**     * 消費資源     */    public synchronized void destroy() {        while (!flag) {            try {                wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        System.out.println(Thread.currentThread().getName() + "消費者****" + number);        flag = false;        notify();    }}

再次發現問題

  • 列印到某個值比如生產完74,程式運行卡死了,好像鎖死了一樣。

原因分析

  • notify:只能喚醒一個線程,如果本方喚醒了本方,沒有意義。而且while判斷標記+notify會導致”死結”。

解決方案

  • notifyAll解決了本方線程一定會喚醒對方線程的問題。

 

最後代碼改進(Resource中的notify()->notifyAll()) 

Resource.java

/** * Created by yuandl on 2016-10-11./** * 資源 */public class Resource {    /*資源序號*/    private int number = 0;    /*資源標記*/    private boolean flag = false;    /**     * 生產資源     */    public synchronized void create() {        while (flag) {//先判斷標記是否已經生產了,如果已經生產,等待消費;            try {                wait();//讓生產線程等待            } catch (InterruptedException e) {                e.printStackTrace();            }        }        number++;//生產一個        System.out.println(Thread.currentThread().getName() + "生產者------------" + number);        flag = true;//將資源標記為已經生產        notifyAll();//喚醒在等待操作資源的線程(隊列)    }    /**     * 消費資源     */    public synchronized void destroy() {        while (!flag) {            try {                wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        System.out.println(Thread.currentThread().getName() + "消費者****" + number);        flag = false;        notifyAll();    }}

運行結果:

Thread-0生產者------------412Thread-2消費者****412Thread-0生產者------------413Thread-3消費者****413Thread-1生產者------------414Thread-2消費者****414Thread-1生產者------------415Thread-2消費者****415Thread-0生產者------------416Thread-3消費者****416Thread-1生產者------------417Thread-3消費者****417Thread-0生產者------------418Thread-2消費者****418Thread-0生產者------------419Thread-3消費者****419Thread-1生產者------------420Thread-2消費者****420

以上就大功告成了,沒有任何問題

原文地址:http://www.manongjc.com/article/1583.html

Java多線程之並發協作生產者消費者設計模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.