文章目錄
概述
高并發編程-線程通信_使用wait和notify進行線程間的通信2_多生產者多消費者導致程序假死原因分析 中分析了假死的原因,這里我們來看下改如何解決在多線程下出現的這個問題呢?
解決辦法
多線程情況用while而不是if 來判斷條件是否滿足notify —> notifyAll
package com
.artisan
.test
;import java
.util
.stream
.Stream
;public class MultiProduceConsumerDemo2 {private final Object LOCK
= new Object();private boolean isProduced
= false;private volatile int i
= 0;public void produce() {synchronized (LOCK
) {String msg
= isProduced
? "已生產貨物" : "沒有貨物可搬運";while (isProduced
) {try {System
.out
.println(Thread
.currentThread().getName() + " GOT LOCK ,isProduced= " + isProduced
+ " wait becauseof " + msg
);LOCK
.wait();} catch (InterruptedException e
) {e
.printStackTrace();}}i
++;System
.out
.println(Thread
.currentThread().getName() + " GOT LOCK ,isProduced= " + isProduced
+ " Produce:" + i
);LOCK
.notifyAll();isProduced
= true;}}public void consume() {synchronized (LOCK
) {String msg
= isProduced
? "已生產貨物" : "沒有貨物可搬運";while (!isProduced
) {try {System
.out
.println(Thread
.currentThread().getName() + " wait becauseof " + msg
);LOCK
.wait();} catch (InterruptedException e
) {e
.printStackTrace();}}System
.out
.println(Thread
.currentThread().getName() + " GOT LOCK ,isProduced= " + isProduced
+ " Consume:" + i
);LOCK
.notifyAll();isProduced
= false;}}public static void main(String
[] args
) {MultiProduceConsumerDemo2 produceConsumerDemo
= new MultiProduceConsumerDemo2();Stream
.of("P1", "P2").forEach(n
-> new Thread(n
) {@Overridepublic void run() {while (true) produceConsumerDemo
.produce();}}.start());Stream
.of("C1", "C2").forEach(n
-> new Thread(n
) {@Overridepublic void run() {while (true) produceConsumerDemo
.consume();}}.start());}
}
總結
以上是生活随笔為你收集整理的高并发编程-使用wait和notifyAll进行线程间的通信3_多线程下的生产者消费者模型和notifyAll的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。