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