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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

多线程学习(九)-可阻塞的队列

發布時間:2024/3/13 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 多线程学习(九)-可阻塞的队列 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

阻塞隊列與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();}}}}

總結

以上是生活随笔為你收集整理的多线程学习(九)-可阻塞的队列的全部內容,希望文章能夠幫你解決所遇到的問題。

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