阻塞隊列和非阻塞的區別:如果隊列裡面已經放滿了,如果是阻塞隊列那麼線程會一直阻塞,而非阻塞對壘則會拋出異常.隊列還包括固定長度的隊列和不固定長度的隊列.這個類實現了BlockingQueue這個介面有如下方法:
拿Insert情況來說,如果隊列裡面已經滿了,使用add方法往裡放就會拋出異常,用offer放回false,用put()方法將會阻塞在那裡,知道有空間可以放.下面來看一個例子:public class BlockingQueueTest {
public static void main(String[] args) { final BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(3);//該隊列裡面只能放3個Integer 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(); }
}
運行結果:
我們可以通過使用兩個都是一個控制項的緩衝隊列來實現同步通知的功能. 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 k){//不能加上synchronized,可能會導致死結,put方法會阻塞但是不會釋放鎖 try { queue2.put(1);//第一次執行的時候因為已經滿了,就阻塞 } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 1; i <= 10; i++) { System.out.println("sub thread sequence " + i + " loop of " + k); } try { queue1.take();//這樣queue1就可以put了 } catch (InterruptedException e) { e.printStackTrace(); } } public void main(int k) {//不能加上synchronized,可能會導致死結,put方法會阻塞但是不會釋放鎖 try { queue1.put(1);//可以放 } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 1; i <= 100; i++) { System.out.println("main thread sequence " + i + " loop of " + k); } try { queue2.take();//這樣queue2就可以put了 } catch (InterruptedException e) { e.printStackTrace(); } }
}
這樣也能實現主線程和子線程之間的列印切換.轉載請註明出處 : http://blog.csdn.net/johnny901114/article/details/8696026