日本免费全黄少妇一区二区三区-高清无码一区二区三区四区-欧美中文字幕日韩在线观看-国产福利诱惑在线网站-国产中文字幕一区在线-亚洲欧美精品日韩一区-久久国产精品国产精品国产-国产精久久久久久一区二区三区-欧美亚洲国产精品久久久久

初學(xué)者java入門基礎(chǔ)知識(shí) java雙端隊(duì)列原理( 三 )


非阻塞隊(duì)列ConcurrentLinkedQueue 是一個(gè)基于鏈接節(jié)點(diǎn)的無界線程安全隊(duì)列 , 它采用先進(jìn)先出的規(guī)則對(duì)節(jié)點(diǎn)進(jìn)行排序 , 當(dāng)我們添加一個(gè)元素的時(shí)候 , 它會(huì)添加到隊(duì)列的尾部;當(dāng)我們獲取一個(gè)元素時(shí) , 它會(huì)返回隊(duì)列頭部的元素 。它的入隊(duì)和出隊(duì)操作均利用 CAS(Compare And Set)更新 , 這樣允許多個(gè)線程并發(fā)執(zhí)行 , 并且不會(huì)因?yàn)榧渔i而阻塞線程 , 使得并發(fā)性能更好 。ConcurrentLinkedQueue 使用示例:
ConcurrentLinkedQueue concurrentLinkedQueue = new ConcurrentLinkedQueue();concurrentLinkedQueue.add("Dog");concurrentLinkedQueue.add("Cat");while (!concurrentLinkedQueue.isEmpty()) {System.out.println(concurrentLinkedQueue.poll());}執(zhí)行結(jié)果:

Dog
Cat
可以看出不管是阻塞隊(duì)列還是非阻塞隊(duì)列 , 使用方法都是類似的 , 區(qū)別是底層的實(shí)現(xiàn)方式 。
優(yōu)先級(jí)隊(duì)列PriorityQueue 一個(gè)基于優(yōu)先級(jí)堆的無界優(yōu)先級(jí)隊(duì)列 。優(yōu)先級(jí)隊(duì)列的元素按照其自然順序進(jìn)行排序 , 或者根據(jù)構(gòu)造隊(duì)列時(shí)提供的 Comparator 進(jìn)行排序 , 具體取決于所使用的構(gòu)造方法 。優(yōu)先級(jí)隊(duì)列不允許使用 null 元素 。PriorityQueue 代碼使用示例:
Queue<Integer> priorityQueue = new PriorityQueue(new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {// 非自然排序 , 數(shù)字倒序return o2 - o1;}});priorityQueue.add(3);priorityQueue.add(1);priorityQueue.add(2);while (!priorityQueue.isEmpty()) {Integer i = priorityQueue.poll();System.out.println(i);}程序執(zhí)行的結(jié)果是:
3
2
1
PriorityQueue 注意的點(diǎn):
  1. PriorityQueue 是非線程安全的 , 在多線程情況下可使用 PriorityBlockingQueue 類替代;
  2. PriorityQueue 不允許插入 null 元素 。
相關(guān)面試題1.ArrayBlockingQueue 和 LinkedBlockingQueue 的區(qū)別是什么?答:ArrayBlockingQueue 和 LinkedBlockingQueue 都實(shí)現(xiàn)自阻塞隊(duì)列 BlockingQueue , 它們的區(qū)別主要體現(xiàn)在以下幾個(gè)方面:
  • ArrayBlockingQueue 使用時(shí)必須指定容量值 , LinkedBlockingQueue 可以不用指定;
  • ArrayBlockingQueue 的最大容量值是使用時(shí)指定的 , 并且指定之后就不允許修改;而 LinkedBlockingQueue 最大的容量為 Integer.MAX_VALUE;
  • ArrayBlockingQueue 數(shù)據(jù)存儲(chǔ)容器是采用數(shù)組存儲(chǔ)的;而 LinkedBlockingQueue 采用的是 Node 節(jié)點(diǎn)存儲(chǔ)的 。
2.LinkedList 中 add() 和 offer() 有什么關(guān)系?答:add() 和 offer() 都是添加元素到隊(duì)列尾部 。offer 方法是基于 add 方法實(shí)現(xiàn)的 , Offer 的源碼如下:
public boolean offer(E e) {return add(e);}3.Queue 和 Deque 有什么區(qū)別?答:Queue 屬于一般隊(duì)列 , Deque 屬于雙端隊(duì)列 。一般隊(duì)列是先進(jìn)先出 , 也就是只有先進(jìn)的才能先出;而雙端隊(duì)列則是兩端都能插入和刪除元素 。
4.LinkedList 屬于一般隊(duì)列還是雙端隊(duì)列?答:LinkedList 實(shí)現(xiàn)了 Deque 屬于雙端隊(duì)列 , 因此擁有 addFirst(E)、addLast(E)、getFirst()、getLast() 等方法 。
5.以下說法錯(cuò)誤的是?A:DelayQueue 內(nèi)部是基于 PriorityQueue 實(shí)現(xiàn)的 B:PriorityBlockingQueue 不是先進(jìn)先出的數(shù)據(jù)存儲(chǔ)方式 C:LinkedBlockingQueue 容量是無限大的 D:ArrayBlockingQueue 內(nèi)部的存儲(chǔ)單元是數(shù)組 , 初始化時(shí)必須指定隊(duì)列容量 答:C 題目解析:LinkedBlockingQueue 默認(rèn)容量是 Integer.MAX_VALUE , 并不是無限大的 , 源碼如下圖所示:

初學(xué)者java入門基礎(chǔ)知識(shí) java雙端隊(duì)列原理

推薦閱讀