Java多线程之线程并发库阻塞队列的应用
生活随笔
收集整理的這篇文章主要介紹了
Java多线程之线程并发库阻塞队列的应用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ArrayBlockingQueue(jdk中已經提供 就在那個condition類說明里的可阻塞示例程序的下面就說明了)
注意三個添加方法的區別->查API文檔 拿插入來說 一個會拋異常 一個返回true/false 一個會阻塞
是記不住的 找到doc即可 把精力留出來吧
阻塞隊列與Semaphore有些相似,但也不同,阻塞隊列是一方存放數據,另一方釋放數據,Semaphore通常則是由同一方設置和釋放信號量。
用3個空間的隊列來演示阻塞隊列的功能和效果。?
?
package javaplay.thread.test;import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue;public class BlockingQueueTest {public static void main(String[] args) {final BlockingQueue<Integer> 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,觀察運行結果會發現經常會有3個數據 100則因取得快很少有3Thread.sleep(1000);System.out.println(Thread.currentThread().getName() + "準備取數據!");queue.take();System.out.println(Thread.currentThread().getName() + "已經取走數據," + "隊列目前有" + queue.size() + "個數據");} catch (InterruptedException e) {e.printStackTrace();}}}}.start();} }用兩個具有1個空間的隊列來實現同步通知的功能。
?
?
package javaplay.thread.test;import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue;public class BlockingQueueCommunication {public static void main(String[] args) {final Business business = new Business();new Thread(new Runnable() {@Overridepublic void run() {for (int i = 1; i <= 5; i++) {business.sub(i);}}}).start();for (int i = 1; i <= 5; i++) {business.main(i);}}static class Business {BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<Integer>(1);BlockingQueue<Integer> queue2 = new ArrayBlockingQueue<Integer>(1);{// 此處不能加static(queue1/queue2都不是static) 這叫匿名構造方法 運行時機在任何構造方法之前// Collections.synchronizedMap(null);try {System.out.println("xxxxxdfsdsafdsa");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 <= 1; 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) {// 此處不能加synchronized 否則如果main先進去就死鎖了try {queue2.put(1);} catch (InterruptedException e1) {e1.printStackTrace();}for (int j = 1; j <= 2; j++) {System.out.println("main thread sequece of " + j + ",loop of " + i);}try {queue1.take();} catch (InterruptedException e) {e.printStackTrace();}}}}一個隊列可否實現呢?
?
轉載于:https://www.cnblogs.com/john8169/p/9780546.html
總結
以上是生活随笔為你收集整理的Java多线程之线程并发库阻塞队列的应用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: noip2016考前模板
- 下一篇: 用C++对C++语法格式进行分析