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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

如何手撸一个队列?队列详解和面试题汇总(含答案)

發布時間:2025/3/11 编程问答 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何手撸一个队列?队列详解和面试题汇总(含答案) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

隊列(Queue):與棧相對的一種數據結構, 集合(Collection)的一個子類。隊列允許在一端進行插入操作,而在另一端進行刪除操作的線性表,棧的特點是后進先出,而隊列的特點是先進先出。隊列的用處很大,比如實現消息隊列。Queue 類關系圖,如下圖所示:注:為了讓讀者更直觀地理解,上圖為精簡版的 Queue 類關系圖。本文如無特殊說明,內容都是基于 Java 1.8 版本。?

隊列(Queue)

1)Queue 分類

從上圖可以看出 Queue 大體可分為以下三類。

  • 雙端隊列:雙端隊列(Deque)是 Queue 的子類也是 Queue 的補充類,頭部和尾部都支持元素插入和獲取。

  • 阻塞隊列:阻塞隊列指的是在元素操作時(添加或刪除),如果沒有成功,會阻塞等待執行。例如,當添加元素時,如果隊列元素已滿,隊列會阻塞等待直到有空位時再插入。

  • 非阻塞隊列:非阻塞隊列和阻塞隊列相反,會直接返回操作的結果,而非阻塞等待。雙端隊列也屬于非阻塞隊列。

  • 2)Queue 方法說明

    Queue 常用方法,如下圖所示:

    方法說明:

    • add(E):添加元素到隊列尾部,成功返回 true,隊列超出時拋出異常;

    • offer(E):添加元素到隊列尾部,成功返回 true,隊列超出時返回 false;

    • remove():刪除元素,成功返回 true,失敗返回 false;

    • poll():獲取并移除此隊列的第一個元素,若隊列為空,則返回 null;

    • peek():獲取但不移除此隊列的第一個元素,若隊列為空,則返回 null;

    • element():獲取但不移除此隊列的第一個元素,若隊列為空,則拋異常。

    3)Queue 使用實例

    Queue<String> linkedList = new LinkedList<>(); linkedList.add("Dog"); linkedList.add("Camel"); linkedList.add("Cat"); while (!linkedList.isEmpty()) {System.out.println(linkedList.poll()); }

    程序執行結果:

    Dog Camel Cat

    阻塞隊列

    1)BlockingQueue

    BlockingQueue 在 java.util.concurrent 包下,其他阻塞類都實現自 BlockingQueue 接口,BlockingQueue 提供了線程安全的隊列訪問方式,當向隊列中插入數據時,如果隊列已滿,線程則會阻塞等待隊列中元素被取出后再插入;當從隊列中取數據時,如果隊列為空,則線程會阻塞等待隊列中有新元素再獲取。BlockingQueue?核心方法插入方法:

    • add(E):添加元素到隊列尾部,成功返回 true,隊列超出時拋出異常;

    • offer(E):添加元素到隊列尾部,成功返回 true,隊列超出時返回 false ;

    • put(E):將元素插入到隊列的尾部,如果該隊列已滿,則一直阻塞。

    刪除方法:

    • remove(Object):移除指定元素,成功返回 true,失敗返回 false;

    • poll():?獲取并移除隊列的第一個元素,如果隊列為空,則返回 null;

    • take():獲取并移除隊列第一個元素,如果沒有元素則一直阻塞。

    檢查方法:

    • peek():獲取但不移除隊列的第一個元素,若隊列為空,則返回 null。

    2)LinkedBlockingQueue

    LinkedBlockingQueue 是一個由鏈表實現的有界阻塞隊列,容量默認值為 Integer.MAX_VALUE,也可以自定義容量,建議指定容量大小,默認大小在添加速度大于刪除速度情況下有造成內存溢出的風險,LinkedBlockingQueue 是先進先出的方式存儲元素。

    3)ArrayBlockingQueue

    ArrayBlockingQueue 是一個有邊界的阻塞隊列,它的內部實現是一個數組。它的容量是有限的,我們必須在其初始化的時候指定它的容量大小,容量大小一旦指定就不可改變。ArrayBlockingQueue 也是先進先出的方式存儲數據,ArrayBlockingQueue 內部的阻塞隊列是通過重入鎖 ReenterLock 和 Condition 條件隊列實現的,因此 ArrayBlockingQueue 中的元素存在公平訪問與非公平訪問的區別,對于公平訪問隊列,被阻塞的線程可以按照阻塞的先后順序訪問隊列,即先阻塞的線程先訪問隊列。而非公平隊列,當隊列可用時,阻塞的線程將進入爭奪訪問資源的競爭中,也就是說誰先搶到誰就執行,沒有固定的先后順序。示例代碼如下:

    // 默認非公平阻塞隊列 ArrayBlockingQueue queue = new ArrayBlockingQueue(6); // 公平阻塞隊列 ArrayBlockingQueue queue2 = new ArrayBlockingQueue(6,true); // ArrayBlockingQueue 源碼展示 public ArrayBlockingQueue(int capacity) {this(capacity, false); } public ArrayBlockingQueue(int capacity, boolean fair) {if (capacity <= 0)throw new IllegalArgumentException();this.items = new Object[capacity];lock = new ReentrantLock(fair);notEmpty = lock.newCondition();notFull = lock.newCondition(); }

    4)DelayQueue

    DelayQueue 是一個支持延時獲取元素的無界阻塞隊列,隊列中的元素必須實現 Delayed 接口,在創建元素時可以指定延遲時間,只有到達了延遲的時間之后,才能獲取到該元素。實現了 Delayed 接口必須重寫兩個方法?,getDelay(TimeUnit) 和 compareTo(Delayed),如下代碼所示:

    class DelayElement implements Delayed {@Override// 獲取剩余時間public long getDelay(TimeUnit unit) {// do something}@Override// 隊列里元素的排序依據public int compareTo(Delayed o) {// do something}}

    DelayQueue 使用的完整示例,請參考以下代碼:

    public class DelayTest {public static void main(String[] args) throws InterruptedException {DelayQueue delayQueue = new DelayQueue();delayQueue.put(new DelayElement(1000));delayQueue.put(new DelayElement(3000));delayQueue.put(new DelayElement(5000));System.out.println("開始時間:" + DateFormat.getDateTimeInstance().format(new Date()));while (!delayQueue.isEmpty()){System.out.println(delayQueue.take());}System.out.println("結束時間:" + DateFormat.getDateTimeInstance().format(new Date()));}static class DelayElement implements Delayed {// 延遲截止時間(單面:毫秒)long delayTime = System.currentTimeMillis();public DelayElement(long delayTime) {this.delayTime = (this.delayTime + delayTime);}@Override// 獲取剩余時間public long getDelay(TimeUnit unit) {return unit.convert(delayTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);}@Override// 隊列里元素的排序依據public int compareTo(Delayed o) {if (this.getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS)) {return 1;} else if (this.getDelay(TimeUnit.MILLISECONDS) < o.getDelay(TimeUnit.MILLISECONDS)) {return -1;} else {return 0;}}@Overridepublic String toString() {return DateFormat.getDateTimeInstance().format(new Date(delayTime));}} }

    程序執行結果:

    開始時間:2019-6-13 20:40:38 2019-6-13 20:40:39 2019-6-13 20:40:41 2019-6-13 20:40:43 結束時間:2019-6-13 20:40:43

    非阻塞隊列

    ConcurrentLinkedQueue 是一個基于鏈接節點的無界線程安全隊列,它采用先進先出的規則對節點進行排序,當我們添加一個元素的時候,它會添加到隊列的尾部;當我們獲取一個元素時,它會返回隊列頭部的元素。它的入隊和出隊操作均利用 CAS(Compare And Set)更新,這樣允許多個線程并發執行,并且不會因為加鎖而阻塞線程,使得并發性能更好。ConcurrentLinkedQueue 使用示例:

    ConcurrentLinkedQueue concurrentLinkedQueue = new ConcurrentLinkedQueue(); concurrentLinkedQueue.add("Dog"); concurrentLinkedQueue.add("Cat"); while (!concurrentLinkedQueue.isEmpty()) {System.out.println(concurrentLinkedQueue.poll()); }

    執行結果:

    Dog Cat

    可以看出不管是阻塞隊列還是非阻塞隊列,使用方法都是類似的,區別是底層的實現方式。

    優先級隊列

    PriorityQueue 一個基于優先級堆的無界優先級隊列。優先級隊列的元素按照其自然順序進行排序,或者根據構造隊列時提供的 Comparator 進行排序,具體取決于所使用的構造方法。優先級隊列不允許使用 null 元素。PriorityQueue??代碼使用示例

    Queue<Integer> priorityQueue = new PriorityQueue(new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {// 非自然排序,數字倒序return o2 - o1;} }); priorityQueue.add(3); priorityQueue.add(1); priorityQueue.add(2); while (!priorityQueue.isEmpty()) {Integer i = priorityQueue.poll();System.out.println(i); }

    程序執行的結果是:

    3 2 1

    PriorityQueue 注意的點

  • PriorityQueue 是非線程安全的,在多線程情況下可使用 PriorityBlockingQueue 類替代;

  • PriorityQueue 不允許插入 null 元素。

  • 相關面試題

    1.ArrayBlockingQueue 和 LinkedBlockingQueue 的區別是什么?

    答:ArrayBlockingQueue 和 LinkedBlockingQueue 都實現自阻塞隊列 BlockingQueue,它們的區別主要體現在以下幾個方面:

    • ArrayBlockingQueue 使用時必須指定容量值,LinkedBlockingQueue 可以不用指定;

    • ArrayBlockingQueue 的最大容量值是使用時指定的,并且指定之后就不允許修改;而 LinkedBlockingQueue 最大的容量為 Integer.MAX_VALUE;

    • ArrayBlockingQueue 數據存儲容器是采用數組存儲的;而 LinkedBlockingQueue 采用的是 Node 節點存儲的。

    2.LinkedList 中 add() 和 offer() 有什么關系?

    答:add() 和 offer() 都是添加元素到隊列尾部。offer 方法是基于 add 方法實現的,Offer 的源碼如下:

    public boolean offer(E e) {return add(e); }

    3.Queue 和 Deque 有什么區別?

    答:Queue 屬于一般隊列,Deque 屬于雙端隊列。一般隊列是先進先出,也就是只有先進的才能先出;而雙端隊列則是兩端都能插入和刪除元素。

    4.LinkedList 屬于一般隊列還是雙端隊列?

    答:LinkedList 實現了 Deque 屬于雙端隊列,因此擁有 addFirst(E)、addLast(E)、getFirst()、getLast() 等方法。

    5.以下說法錯誤的是?

    A:DelayQueue 內部是基于 PriorityQueue 實現的 B:PriorityBlockingQueue 不是先進先出的數據存儲方式 C:LinkedBlockingQueue 容量是無限大的 D:ArrayBlockingQueue 內部的存儲單元是數組,初始化時必須指定隊列容量 答:C 題目解析:LinkedBlockingQueue 默認容量是 Integer.MAX_VALUE,并不是無限大的,源碼如下圖所示:

    6.關于 ArrayBlockingQueue 說法不正確的是?

    A:ArrayBlockingQueue 是線程安全的 B:ArrayBlockingQueue 元素允許為 null C:ArrayBlockingQueue 主要應用場景是“生產者-消費者”模型 D:ArrayBlockingQueue 必須顯示地設置容量 答:B 題目解析:ArrayBlockingQueue 不允許元素為 null,如果添加一個 null 元素,會拋 NullPointerException 異常。

    7.以下程序執行的結果是什么?

    PriorityQueue priorityQueue = new PriorityQueue(); priorityQueue.add(null); System.out.println(priorityQueue.size());

    答:程序執行報錯,PriorityQueue 不能插入 null。

    8.Java 中常見的阻塞隊列有哪些?

    答:Java 中常見的阻塞隊列如下:

    • ArrayBlockingQueue,由數組結構組成的有界阻塞隊列;

    • PriorityBlockingQueue,支持優先級排序的無界阻塞隊列;

    • SynchronousQueue,是一個不存儲元素的阻塞隊列,會直接將任務交給消費者,必須等隊列中的添加元素被消費后才能繼續添加新的元素;

    • LinkedBlockingQueue,由鏈表結構組成的阻塞隊列;

    • DelayQueue,支持延時獲取元素的無界阻塞隊列。

    9.有界隊列和無界隊列有哪些區別?

    答:有界隊列和無界隊列的區別如下:

    • 有界隊列:有固定大小的隊列叫做有界隊列,比如:new ArrayBlockingQueue(6),6 就是隊列的大小。

    • 無界隊列:指的是沒有設置固定大小的隊列,這些隊列的特點是可以直接入列,直到溢出。它們并不是真的無界,它們最大值通常為 Integer.MAXVALUE,只是平常很少能用到這么大的容量(超過 Integer.MAXVALUE),因此從使用者的體驗上,就相當于 “無界”。

    10.如何手動實現一個延遲消息隊列?

    答:說到延遲消息隊列,我們應該可以第一時間想到要使用 DelayQueue 延遲隊列來解決這個問題。實現思路,消息隊列分為生產者和消費者,生產者用于增加消息,消費者用于獲取并消費消息,我們只需要生產者把消息放入到 DelayQueue 隊列并設置延遲時間,消費者循環使用 take() 阻塞獲取消息即可。完整的實現代碼如下:

    public class CustomDelayQueue {// 消息編號static AtomicInteger MESSAGENO = new AtomicInteger(1);public static void main(String[] args) throws InterruptedException {DelayQueue<DelayedElement> delayQueue = new DelayQueue<>();// 生產者1producer(delayQueue, "生產者1");// 生產者2producer(delayQueue, "生產者2");// 消費者consumer(delayQueue);}//生產者private static void producer(DelayQueue<DelayedElement> delayQueue, String name) {new Thread(new Runnable() {@Overridepublic void run() {while (true) {// 產生 1~5 秒的隨機數long time = 1000L * (new Random().nextInt(5) + 1);try {Thread.sleep(time);} catch (InterruptedException e) {e.printStackTrace();}// 組合消息體String message = String.format("%s,消息編號:%s 發送時間:%s 延遲:%s 秒",name, MESSAGENO.getAndIncrement(), DateFormat.getDateTimeInstance().format(new Date()), time / 1000);// 生產消息delayQueue.put(new DelayedElement(message, time));}}}).start();}//消費者private static void consumer(DelayQueue<DelayedElement> delayQueue) {new Thread(new Runnable() {@Overridepublic void run() {while (true) {DelayedElement element = null;try {// 消費消息element = delayQueue.take();System.out.println(element);} catch (InterruptedException e) {e.printStackTrace();}}}}).start();}// 延遲隊列對象static class DelayedElement implements Delayed {// 過期時間(單位:毫秒)long time = System.currentTimeMillis();// 消息體String message;// 參數:delayTime 延遲時間(單位毫秒)public DelayedElement(String message, long delayTime) {this.time += delayTime;this.message = message;}@Override// 獲取過期時間public long getDelay(TimeUnit unit) {return unit.convert(time - System.currentTimeMillis(), TimeUnit.MILLISECONDS);}@Override// 隊列元素排序public int compareTo(Delayed o) {if (this.getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS))return 1;else if (this.getDelay(TimeUnit.MILLISECONDS) < o.getDelay(TimeUnit.MILLISECONDS))return -1;elsereturn 0;}@Overridepublic String toString() {// 打印消息return message + " |執行時間:" + DateFormat.getDateTimeInstance().format(new Date());}} }

    以上程序支持多生產者,執行的結果如下:

    生產者1,消息編號:1 發送時間:2019-6-12 20:38:37 延遲:2 秒 |執行時間:2019-6-12 20:38:39 生產者2,消息編號:2 發送時間:2019-6-12 20:38:37 延遲:2 秒 |執行時間:2019-6-12 20:38:39 生產者1,消息編號:3 發送時間:2019-6-12 20:38:41 延遲:4 秒 |執行時間:2019-6-12 20:38:45 生產者1,消息編號:5 發送時間:2019-6-12 20:38:43 延遲:2 秒 |執行時間:2019-6-12 20:38:45 ......

    總結

    隊列(Queue)按照是否阻塞可分為:阻塞隊列 BlockingQueue 和 非阻塞隊列。其中,雙端隊列 Deque 也屬于非阻塞隊列,雙端隊列除了擁有隊列的先進先出的方法之外,還擁有自己獨有的方法,如 addFirst()、addLast()、getFirst()、getLast() 等,支持首未插入和刪除元素。隊列中比較常用的兩個隊列還有 PriorityQueue(優先級隊列)和 DelayQueue(延遲隊列),可使用延遲隊列來實現延遲消息隊列,這也是面試中比較常考的問題之一。需要面試朋友對延遲隊列一定要做到心中有數,動手寫一個消息隊列也是非常有必要的。

    本文來自:《Java面試全解析》

    【END】

    關注下方二維碼,訂閱更多精彩內容

    總結

    以上是生活随笔為你收集整理的如何手撸一个队列?队列详解和面试题汇总(含答案)的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。