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

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

需求情景

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

涉及問題

  • 同步問題:如何保證同一資源被多個線程併發訪問時的完整性。經常使用的同步方法是採用標記或加鎖機制markdown

  • wait() / nofity() 方法是基類Object的兩個方法,也就意味着全部Java類都會擁有這兩個方法,這樣,咱們就能夠爲任何對象實現同步機制。併發

  • wait()方法:當緩衝區已滿/空時,生產者/消費者線程中止本身的執行,放棄鎖,使本身處於等等狀態,讓其餘線程執行。ide

  • notify()方法:當生產者/消費者向緩衝區放入/取出一個產品時,向其餘等待的線程發出可執行的通知,同時放棄鎖,使本身處於等待狀態。測試

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

Resource.javathis

/**
 * 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.javaspa

/**
 * Created by yuandl on 2016-10-11.
 *
 /**
 * 生產者
 */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.javaorm

/**
 * 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生產者------------1
Thread-1消費者****1
Thread-0生產者------------2
Thread-1消費者****2
Thread-0生產者------------3
Thread-1消費者****3
Thread-0生產者------------4
Thread-1消費者****4
Thread-0生產者------------5
Thread-1消費者****5
Thread-0生產者------------6
Thread-1消費者****6
Thread-0生產者------------7
Thread-1消費者****7
Thread-0生產者------------8
Thread-1消費者****8
Thread-0生產者------------9
Thread-1消費者****9
Thread-0生產者------------10
Thread-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生產者------------100
Thread-3消費者****100
Thread-0生產者------------101
Thread-3消費者****101
Thread-2消費者****101
Thread-1生產者------------102
Thread-3消費者****102
Thread-0生產者------------103
Thread-2消費者****103
Thread-1生產者------------104
Thread-3消費者****104
Thread-1生產者------------105
Thread-0生產者------------106
Thread-2消費者****106
Thread-1生產者------------107
Thread-3消費者****107
Thread-0生產者------------108
Thread-2消費者****108
Thread-0生產者------------109
Thread-2消費者****109
Thread-1生產者------------110
Thread-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生產者------------412
Thread-2消費者****412
Thread-0生產者------------413
Thread-3消費者****413
Thread-1生產者------------414
Thread-2消費者****414
Thread-1生產者------------415
Thread-2消費者****415
Thread-0生產者------------416
Thread-3消費者****416
Thread-1生產者------------417
Thread-3消費者****417
Thread-0生產者------------418
Thread-2消費者****418
Thread-0生產者------------419
Thread-3消費者****419
Thread-1生產者------------420
Thread-2消費者****420

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

相關文章
相關標籤/搜索