JAVA可阻塞队列-ArrayBlockingQueue
生活随笔
收集整理的這篇文章主要介紹了
JAVA可阻塞队列-ArrayBlockingQueue
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在前面的的文章,寫了一個帶有緩沖區的隊列,是用JAVA的Lock下的Condition實現的,但是JAVA類中提供了這項功能,就是ArrayBlockingQueue,
ArrayBlockingQueue是由數組支持的有界阻塞隊列,次隊列按照FIFO(先進先出)原則,當隊列已經填滿,在去增加則會導致阻塞,這種阻塞類似線程阻塞。
ArrayBlockingQueue提供的增加和取出方法總結
| ? | 拋異常 | 返回值 | 阻塞 | 超時 |
| Insert | Add(e) | offer(e) | put(e) | offer(e,time,unit) |
| remove | remove() | poll() | take() | poll(time,unit) |
| Examine | element() | peek() | 空 | 空 |
使用ArrayBlockingQueue的一個子類BlockingQueue實現一個可阻塞隊列,一個線程put另一個線程take,當隊列為空時take等待,當線程滿時put等待
此實現方式沒有線程互斥
import java.util.Random; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue;/*** 可阻塞的隊列* BlockingQueue* 此方式不能實現線程互斥* @author**/ public class BlockingQueueCommunicationTest {public static void main(String[] args) {final BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(3);new Thread(new Runnable() {@Overridepublic void run() {while (true) {try {Thread.sleep(new Random().nextInt(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(new Runnable() {@Overridepublic void run() {while (true) {try {Thread.sleep(new Random().nextInt(1000));System.out.println("線程"+ Thread.currentThread().getName() + "準備取走");queue.take();System.out.println("線程"+ Thread.currentThread().getName() + "已取走,隊列剩余"+ queue.size() + "個");} catch (InterruptedException e) {e.printStackTrace();}}}}).start();} }?
轉載于:https://www.cnblogs.com/duwenlei/p/5129298.html
總結
以上是生活随笔為你收集整理的JAVA可阻塞队列-ArrayBlockingQueue的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java绿盾解密- Ldterm(绿盾加
- 下一篇: 求任意一个点到任意函数曲线或曲线方程(参