多线程学习(九)-可阻塞的队列
生活随笔
收集整理的這篇文章主要介紹了
多线程学习(九)-可阻塞的队列
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
阻塞隊列與Semaphore有些相似,但也不同,阻塞隊列是一方存放數據,另一方釋放數據,Semaphore通常則是由同一方設置和釋放信號量。
ArrayBlockingQueue只有put方法和take方法才具有阻塞功能
在java.util.concurrent.Lock接口中實現了一個阻塞的緩沖區,在上面的一篇博客有介紹:阻塞隊列的一個實現。
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(); } }????????????????????????
2.應用:用阻塞隊列實現線程同步通信
前面有博客介紹線程同步通信的實現就可以用阻塞隊列實現。
線程同步通信實現的另外兩種方式的例子
import java.util.Collections; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.atomic.AtomicInteger;public class BlockingQueueCommunication {/*** @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 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 sequece of " + j + ",loop of " + i);}try {queue2.take();} catch (InterruptedException e) {e.printStackTrace();}}public void main(int i){try {queue2.put(1);} catch (InterruptedException e1) {e1.printStackTrace();}for(int j=1;j<=100;j++){System.out.println("main thread sequece of " + j + ",loop of " + i);}try {queue1.take();} catch (InterruptedException e) {e.printStackTrace();}}}}
總結
以上是生活随笔為你收集整理的多线程学习(九)-可阻塞的队列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spy++是可以获取浏览器当前页面的标题
- 下一篇: 特种浓缩分离:倒极电渗析技术工作原理介绍