java - LinkedBlockingQueue 阻塞问题
伊谢尔伦
伊谢尔伦 2017-04-18 09:44:43
0
4
1028

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

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

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

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(4)
洪涛

Automatic acquisition, no blocking

伊谢尔伦

If it is still blocking, what is the use of this class?

巴扎黑

It is recommended to look at the source code and you will know, it is very beneficial

伊谢尔伦

@wxmimperio The answer you adopted is wrong. ConcurrentLinkedQueue is non-blocking, and LinkedBlockingQueue is blocking. I will give you the codes respectively: as follows:

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

But look at the non-blocking 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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!