日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

生产者-消费者 BlockingQueue 运用示例

發布時間:2024/7/23 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 生产者-消费者 BlockingQueue 运用示例 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

簡單說明:

1、生產者負責將字符串轉換成int 數字放入BlockingQueue,失敗就停止生產消費線程。

2、消費者從BlockingQueue獲得數字,取平方根值,并累積值。如果有負數,失敗!停止生產消費線程。

3、模擬一個生產者,2個消費者。為了能均衡對應,生產者每次暫停 10毫秒,消費每次暫停23 毫秒~~

代碼:

public class ThreadTest {private final BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>( 5 );/**計算結果**/private final AtomicInteger atoInt = new AtomicInteger(0);/**整個計算過程是否成功**/private final AtomicBoolean isSuccess = new AtomicBoolean(true);private Thread t1 = null;private Thread t2 = null;private Thread t3 = null;private final CountDownLatch endGate = new CountDownLatch( 2 );public static void main(String[] args) throws InterruptedException {String[] data = new String[]{ "1", "1", "4", "9", "25", "36", "49", "64", "81", "144"};ThreadTest test = new ThreadTest();Producter p = test.new Producter(data);Consumer c1 = test.new Consumer();Consumer c2 = test.new Consumer();test.t1 = new Thread(p);test.t2 = new Thread(c1);test.t3 = new Thread(c2);test.start();test.endGate.await();if( test.isSuccess.get() ){System.out.println( "計算結果:" + test.atoInt.get() );}else{System.out.println( "計算過程中遇到錯誤!" );}}private void start(){t1.start();t2.start();t3.start();}private void stop(){t1.interrupt();t2.interrupt();t3.interrupt();}private class Producter implements Runnable{private final String[] data;public Producter(String[] data) {super();this.data = data;}@Overridepublic void run() {try {for( String s : data ){//System.out.println( "當前讀取數:" + s );int i = Integer.valueOf( s );queue.put( i );Thread.sleep( 10 );}queue.put( Integer.MAX_VALUE );} catch (NumberFormatException e) {e.printStackTrace();isSuccess.set(false);stop();return;} catch (InterruptedException e) {Thread.currentThread().interrupt();}}}private class Consumer implements Runnable{@Overridepublic void run() {try {while( !Thread.currentThread().isInterrupted() ){int i = queue.take();Thread.sleep( 23 );//遇到錯誤值if( i<0 ){stop();isSuccess.set(false);break;}//結束標志else if( i == Integer.MAX_VALUE ){stop();break;}//System.out.println( Thread.currentThread() + "當前queue獲取數:" + i );atoInt.addAndGet( (int)Math.sqrt(i) );//System.out.println( atoInt.get() );}} catch (InterruptedException e) {Thread.currentThread().interrupt();}finally{endGate.countDown();}}} }


?

總結

以上是生活随笔為你收集整理的生产者-消费者 BlockingQueue 运用示例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。