JUC 阻塞队列

一、用法

方法类型   异常抛出   特殊值   阻塞   超时
  插入              add(e)     offer(e)        put(e)       offer(e,time,unit)
      移除        remove()   poll()        take()       poll(time,unit)
      检查        element()        peek()        不可用       不可用

二、案例

 

package com.wt.queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @Description: TODO
 * @Author: 1872428
 * @Date: 2025/6/2 11:38
 * @Version: 1.0
 **/
public class Demon01 {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> queue = new ArrayBlockingQueue<String>(3);
        // 方案一 add remove ,报错
       /* System.out.println(queue.add("a"));
        System.out.println(queue.add("b"));
        System.out.println(queue.add("c"));
        //System.out.println(queue.add("d"));
        System.out.println(queue.element());
        System.out.println(queue.remove());
        System.out.println(queue.remove());
        System.out.println(queue.remove());
        //System.out.println(queue.remove());*/

        // 方案二 offer poll , offer 返回 false poll 返回 null
      /*  System.out.println(queue.offer("a"));
        System.out.println(queue.offer("b"));
        System.out.println(queue.offer("c"));
        System.out.println(queue.offer("d"));
        //System.out.println(queue.peek());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());*/

        // 方案三 put take 挂起
       /* queue.put("a");
        queue.put("b");
        queue.put("c");
        //queue.put("d");
        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());*/
        // 方案四
        queue.offer("a");
        queue.offer("b");
        queue.offer("c");
        queue.offer("d", 3L, TimeUnit.SECONDS);
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll(3L, TimeUnit.SECONDS));

    }
}

 

posted @ 2025-06-02 14:11  市丸银  阅读(6)  评论(0)    收藏  举报