搜尋

首頁  >  問答  >  主體

java - LinkedBlockingQueue 阻塞问题

当用LinkedBlockingQueue的take()方法获取队列信息时

一旦队列为空,则进入阻塞状态

再往队列里put()元素,take()方法会自动获取新加入元素,还是始终保持阻塞状态?

伊谢尔伦伊谢尔伦2856 天前1066

全部回覆(4)我來回復

  • PHP中文网

    PHP中文网2017-04-18 09:46:43

    自動獲取,不會阻塞了

    回覆
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:46:43

    如果還是阻塞,這個類別還有什麼用?

    回覆
    0
  • 巴扎黑

    巴扎黑2017-04-18 09:46:43

    建議看看源碼,就知道了,很有好處的

    回覆
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:46:43

    @wxmimperio 你採納的答案是錯的。 ConcurrentLinkedQueue是不阻塞的,LinkedBlockingQueue是阻塞的。分別給你上程式碼:如下:

    import java.util.concurrent.LinkedBlockingQueue;
    public class TestLinkedBlockingQueue {
        public static void main(String[] args) {
            LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>();
            try {
                queue.put("a");
                queue.put("b");
                System.out.println(queue.take());
                System.out.println(queue.take());
                System.out.println(queue.take());
                queue.put("c");
                System.out.println(queue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //输出结果:
    //a
    //b
    

    但你再看非阻塞的ConcurrentLinkedQueue

    import java.util.concurrent.ConcurrentLinkedQueue;
    public class TestConcurrentLinkedQueue {
        public static void main(String[] args) {
            ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>();
            queue.add("a");
            queue.add("b");
            System.out.println(queue.peek());
            queue.remove();
            System.out.println(queue.peek());
            queue.remove();
            System.out.println(queue.peek());
            queue.remove();
            queue.add("c");
            System.out.println(queue.peek());
            queue.remove();
        }
    }
    //a
    //b
    //null
    //Exception in thread "main" java.util.NoSuchElementException
    //    at java.util.AbstractQueue.remove(AbstractQueue.java:117)
    //    at TestConcurrentLinkedQueue.main(TestConcurrentLinkedQueue.java:14)

    回覆
    0
  • 取消回覆