程序员必知系列之Collection的阻塞队列

90 阅读1分钟

这是我参与 8 月更文挑战的第 11 天,活动详情查看: 8月更文挑战

1.Collection的阻塞队列

阻塞队列,顾名思义就是当线程获取队列中的元素的时候,会出现阻塞的现象,对应的是线程需要等待。当阻塞队列是空时,从队列中获取元素的操作将会被阻塞;当阻塞队列是满,往队列里添加元素的操作将会被阻塞;

2.Collection的常用队列类

BlockingQueue是Collection的阻塞队列类。ArrayBlockingQueue是其子类。

3.Collection常用队列类的API介绍

根据返回值的处理方法可以分为四种: 1.抛出异常的方法 add、remove、element 2.返回特殊值(插入方法成功返回true,失败返回false;移除方法,成功返回出队列的元素,队列里面没有就返回null) offer、poll、peek 3.阻塞 put、take 当阻塞队列满时,生产者线程继续往队列里put元素,队列会一直阻塞生产线程直到put数据or响应中断退出 当阻塞队列满时,生产者线程继续往队列里take元素,队列会一直阻塞消费线程直到队列可用 3.超时阻塞(当阻塞队列满时,队列会阻塞生产者线程一定时间,超过后限时后生产者线程会退出) offer(e,time,unit) poll(time,unit)

4.代码展示

4.1 抛出异常:

BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);

public class BlockingQueueDemo {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);

        System.out.println(blockingQueue.add("a"));
        System.out.println(blockingQueue.add("a"));
        System.out.println(blockingQueue.add("a"));
        System.out.println(blockingQueue.add("a"));
    }
}

4.2 返回特殊值

public class BlockingQueueDemo {
public static void main(String[] args) {
    BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);

    System.out.println(blockingQueue.offer("a"));
    System.out.println(blockingQueue.offer("a"));
    System.out.println(blockingQueue.offer("a"));
    System.out.println(blockingQueue.offer("a"));

    System.out.println(blockingQueue.peek());

    System.out.println(blockingQueue.poll());
    System.out.println(blockingQueue.poll());
    System.out.println(blockingQueue.poll());
    System.out.println(blockingQueue.poll());
}

}

4.3 阻塞

public class BlockingQueueDemo {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);

        blockingQueue.put("a");
        blockingQueue.put("a");
        blockingQueue.put("a");

        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
    }
}

4.4 超时

public class BlockingQueueDemo {
public static void main(String[] args) throws InterruptedException {
    BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);

    System.out.println(blockingQueue.offer("a", 2, TimeUnit.SECONDS));
    System.out.println(blockingQueue.offer("a", 2, TimeUnit.SECONDS));
    System.out.println(blockingQueue.offer("a", 2, TimeUnit.SECONDS));

    System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
    System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
    System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
    System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
}

}