Java线程队列的使用-LinkedBlockingQueue

喜欢ヅ旅行 2023-10-12 23:10 70阅读 0赞

LinkedBlockingQueue是一种基于链表的阻塞队列,它的内部维护了一个数据节点链表。它可以选择指定容量,也可以不指定。如果不指定,默认容量是Integer.MAX_VALUE,也就是无界队列。它采用分离锁(ReentrantLock)来维护生产者和消费者的同步。

LinkedBlockingQueue可以用于实现无界缓冲区,例如下面的代码创建了一个默认容量的LinkedBlockingQueue,并向其中添加了10个元素。可以看到,插入操作不会被阻塞,因为队列没有容量限制。

  1. import java.util.concurrent.LinkedBlockingQueue;
  2. public class LinkedBlockingQueueDemo {
  3. public static void main(String[] args) {
  4. // 创建一个默认容量的链表阻塞队列
  5. LinkedBlockingQueue<Integer> lbq = new LinkedBlockingQueue<>();
  6. // 向队列中添加10个元素
  7. for (int i = 0; i < 10; i++) {
  8. try {
  9. System.out.println("Trying to put " + i + " into queue");
  10. lbq.put(i);
  11. System.out.println("Successfully put " + i + " into queue");
  12. } catch (InterruptedException e) {
  13. e.printStackTrace();
  14. }
  15. }
  16. }
  17. }

输出结果(部分):

  1. Trying to put 0 into queue
  2. Successfully put 0 into queue
  3. Trying to put 1 into queue
  4. Successfully put 1 into queue
  5. Trying to put 2 into queue
  6. Successfully put 2 into queue
  7. Trying to put 3 into queue
  8. Successfully put 3 into queue
  9. Trying to put 4 into queue
  10. Successfully put 4 into queue
  11. Trying to put 5 into queue
  12. Successfully put 5 into queue
  13. // 此时队列没有满,插入操作不会被阻塞,直到达到Integer.MAX_VALUE的上限

发表评论

表情:
评论列表 (有 0 条评论,70人围观)

还没有评论,来说两句吧...

相关阅读