生产者-消费者 BlockingQueue 运用示例
生活随笔
收集整理的這篇文章主要介紹了
生产者-消费者 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 运用示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 线程Blocked--Synchroni
- 下一篇: 死锁Waiting--DeadLockD