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

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

Queue队列使用

發(fā)布時(shí)間:2025/3/20 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Queue队列使用 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Queue

隊(duì)列,支持阻塞機(jī)制
阻塞放入與得到數(shù)據(jù)

實(shí)現(xiàn)LinkedBlockingQueue
下面的方法put與take

Put
把一個(gè)Object加入到BlockingQueue里面
如果,BlockQueue沒(méi)有空間,調(diào)用此方法的線程被阻斷
直到BlockingQueue里面有空間再繼續(xù)執(zhí)行

Take
取走BlockingQueue里面,排在首位的對(duì)象
如果,BlockingQueue為空,阻斷進(jìn)入等待狀態(tài)
直到BlockingQueue有新的數(shù)據(jù)被加入

package com.bjsxt.base.conn009;import java.util.LinkedList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger;public class MyQueue {// 1 需要一個(gè)承裝元素的集合private LinkedList<Object> list = new LinkedList<Object>();// 2 需要一個(gè)計(jì)數(shù)器private AtomicInteger count = new AtomicInteger(0);// 3 需要制定上限和下限private final int minSize = 0;private final int maxSize;// 4 構(gòu)造方法public MyQueue(int size) {this.maxSize = size;}// 5 初始化一個(gè)對(duì)象 用于加鎖private final Object lock = new Object();// put(anObject):// 把a(bǔ)nObject加到BlockingQueue里,如果BlockQueue沒(méi)有空間,則調(diào)用此方法的線程被阻斷,直到BlockingQueue里面有空間再繼續(xù).public void put(Object obj) {synchronized (lock) {while (count.get() == this.maxSize) {try {lock.wait();} catch (InterruptedException e) {e.printStackTrace();}}// 1 加入元素list.add(obj);// 2 計(jì)數(shù)器累加count.incrementAndGet();// 3 通知另外一個(gè)線程(喚醒)lock.notify();System.out.println("新加入的元素為:" + obj);}}// take:// 取走BlockingQueue里排在首位的對(duì)象,若BlockingQueue為空,阻斷進(jìn)入等待狀態(tài)直到BlockingQueue有新的數(shù)據(jù)被加入.public Object take() {Object ret = null;synchronized (lock) {while (count.get() == this.minSize) {try {lock.wait();} catch (InterruptedException e) {e.printStackTrace();}}// 1 做移除元素操作ret = list.removeFirst();// 2 計(jì)數(shù)器遞減count.decrementAndGet();// 3 喚醒另外一個(gè)線程lock.notify();}return ret;}public int getSize() {return this.count.get();}public static void main(String[] args) {final MyQueue mq = new MyQueue(5);mq.put("a");mq.put("b");mq.put("c");mq.put("d");mq.put("e");System.out.println("當(dāng)前容器的長(zhǎng)度:" + mq.getSize());Thread t1 = new Thread(new Runnable() {@Overridepublic void run() {mq.put("f");mq.put("g");}}, "t1");t1.start();Thread t2 = new Thread(new Runnable() {@Overridepublic void run() {Object o1 = mq.take();System.out.println("移除的元素為:" + o1);Object o2 = mq.take();System.out.println("移除的元素為:" + o2);}}, "t2");try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}t2.start();}}

運(yùn)行

《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀

總結(jié)

以上是生活随笔為你收集整理的Queue队列使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。