生活随笔
收集整理的這篇文章主要介紹了
阻塞队列,来写生产者消费者,生产一个消费一个
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
用阻塞隊列來寫,就不需要程序員來關心什么時候阻塞線程await,什么時候喚醒線程notify()。
類似消息中間件
package JUC
;import java
.util
.concurrent
.ArrayBlockingQueue
;
import java
.util
.concurrent
.BlockingQueue
;
import java
.util
.concurrent
.TimeUnit
;
import java
.util
.concurrent
.atomic
.AtomicInteger
;
class MyResource{private volatile boolean FLAG
= true; private AtomicInteger atomicInteger
= new AtomicInteger(1);BlockingQueue
<String> blockingQueue
= null
;public MyResource(BlockingQueue
<String> blockingQueue
) {this.blockingQueue
= blockingQueue
;System
.out
.println(blockingQueue
.getClass().getName()); }public void myProducer() throws Exception
{String data
= null
;boolean retValue
;while(FLAG
){data
= atomicInteger
.getAndIncrement()+"";retValue
= blockingQueue
.offer(data
,2L
, TimeUnit
.SECONDS
);if (retValue
){System
.out
.println(Thread
.currentThread().getName()+"\t 插入隊列"+data
+"成功");}else {System
.out
.println(Thread
.currentThread().getName()+"\t 插入隊列"+data
+"失敗");}TimeUnit
.SECONDS
.sleep(1);}System
.out
.println(Thread
.currentThread().getName()+"\t大老板叫停,表示FLAG=false,生產動作結束");}public void myConsumer() throws Exception
{String result
= null
;while (FLAG
){result
= blockingQueue
.poll(2L
,TimeUnit
.SECONDS
);if (result
== null
|| result
.equalsIgnoreCase("")){FLAG
= false;System
.out
.println(Thread
.currentThread().getName()+"\t超過2秒鐘沒有取到蛋糕,消費退出");return;}System
.out
.println(Thread
.currentThread().getName()+"\t消費隊列"+result
+"成功");}}public void stop() throws Exception
{this.FLAG
= false;}
}
public class ProdConsumer_BlockQueueDemo {public static void main(String
[] args
) {MyResource myResource
= new MyResource(new ArrayBlockingQueue<>(3));new Thread(()->{System
.out
.println(Thread
.currentThread().getName()+"\t生產線程啟動");try {myResource
.myProducer();} catch (Exception e
) {e
.printStackTrace();}},"producer").start();new Thread(()->{System
.out
.println(Thread
.currentThread().getName()+"\t消費線程啟動");System
.out
.println();System
.out
.println();try {myResource
.myConsumer();System
.out
.println();System
.out
.println();} catch (Exception e
) {e
.printStackTrace();}},"consumer").start();try {TimeUnit
.SECONDS
.sleep(5);} catch (InterruptedException e
) {e
.printStackTrace();}System
.out
.println();System
.out
.println();System
.out
.println("5秒鐘時間到,大老板main線程叫停,游戲結束!");try {myResource
.stop();} catch (Exception e
) {e
.printStackTrace();}}
}
總結
以上是生活随笔為你收集整理的阻塞队列,来写生产者消费者,生产一个消费一个的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。