阻塞隊列案例分享

<code>import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;public class BlockingQueueTest {public static void main(String[] args) {final BlockingQueue queue = new ArrayBlockingQueue(3);for(int i=0;i<2;i++){new Thread(){public void run(){while(true){try {Thread.sleep((long)(Math.random()*1000));System.out.println(Thread.currentThread().getName() + "準備放數據!");queue.put(1);System.out.println(Thread.currentThread().getName() + "已經放了數據," + "隊列目前有" + queue.size() + "個數據");} catch (InterruptedException e) {e.printStackTrace();}}}}.start();}new Thread(){public void run(){while(true){try {//將此處的睡眠時間分別改為100和1000,觀察運行結果Thread.sleep(1000);System.out.println(Thread.currentThread().getName() + "準備取數據!");queue.take();System.out.println(Thread.currentThread().getName() + "已經取走數據," + "隊列目前有" + queue.size() + "個數據");} catch (InterruptedException e) {e.printStackTrace();}}}}.start();}}/<code>

運行結果如下圖所示:

阻塞隊列案例分享

阻塞隊列的運用

<code>package com.chang;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;public class BlockQueueThreadComunication {/** * @param args */public static void main(String[] args) {final Business business = new Business();new Thread(new Runnable() {@Overridepublic void run() {for(int i=1;i<=50;i++){business.sub(i);}}}).start();for(int i=1;i<=50;i++){business.main(i);}}//如果一個內部類用static修飾,那麼這個內部類將會變成外部類static class Business {    BlockingQueue<integer>  queue1= new ArrayBlockingQueue<integer>(1);  BlockingQueue<integer>  queue2 =  new ArrayBlockingQueue<integer>(1);    //匿名構造方法, 創建幾個對象,就會被調用幾次, 而靜態代碼塊只會被調用一次  {  try {queue2.put(1);} catch (InterruptedException e) {e.printStackTrace();}  }      public  void sub(int i){    try {queue1.put(1);} catch (InterruptedException e) {e.printStackTrace();}for(int j=1;j<=10;j++){System.out.println("sub thread sequence of " + j + ",loop of " + i);}try {queue2.take();} catch (InterruptedException e) {e.printStackTrace();}  }    public  void main(int i){  try {queue2.put(1);} catch (InterruptedException e) {e.printStackTrace();}for(int j=1;j<=100;j++){System.out.println("main thread sequence of " + j + ",loop of " + i);}try {queue1.take();} catch (InterruptedException e) {e.printStackTrace();}  }  }}/<integer>/<integer>/<integer>/<integer>/<code>


分享到:


相關文章: