LinkedBlockingQueue也是BlockingQueue接口的一个实现类之一
这个属于基础性问题,老规矩,我们将从使用场景和代码示例来进行讲解
来,思考片刻,给出你的答案
1,使用场景
2,来,上代码
- import java.util.concurrent.LinkedBlockingQueue;
-
- public class LinkedBlockingQueueExample {
- static final LinkedBlockingQueue
queue = new LinkedBlockingQueue<>(); -
- public static void main(String[] args) throws InterruptedException {
- Thread producer = new Thread(() -> {
- try {
- for (int i = 0; i < 20; i++) {
- String item = "Item " + i;
- queue.put(item); // 即使是无界队列,也可以通过put阻塞等待空间
- System.out.println("Produced: " + item);
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- });
-
- Thread consumer = new Thread(() -> {
- try {
- while (true) {
- String item = queue.take(); // 无界队列情况下,take永远不会阻塞,直到被中断
- System.out.println("Consumed: " + item);
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- });
-
- producer.start();
- consumer.start();
-
- // 等待producer完成
- producer.join();
- // 中断消费者
- consumer.interrupt();
- }
- }
想提高面试准备效率!欢迎来加入我的星球!承诺三天内不满意,直接免费退出!
