简体   繁体   English

PriorityBlockingQueue 的目的是什么?

[英]What's the purpose of the PriorityBlockingQueue?

I've been playing with blocking queues and PriorityQueue , and it got me thinking.我一直在阻塞队列和PriorityQueue ,这让我开始思考。 I can't see a good usecase for PriorityBlockingQueue .我看不到PriorityBlockingQueue的好用例。 The point of a priority queue is to sort the values put into it before they're retrieved.优先级队列的要点是在检索之前对放入其中的值进行排序。 A blocking queue implies that values are inserted into it and retrieved from it concurrently.阻塞队列意味着将值插入其中并同时从中检索。 But, if that's the case, you'd never be able to guarantee the sort order.但是,如果是这种情况,您将永远无法保证排序顺序。

BlockingQueue<Integer> q = new PriorityBlockingQueue<>();

new Thread (()->{ randomSleep(); q.put(2); randomSleep(); q.put(0); }).start();
new Thread (()->{ randomSleep(); q.put(3); randomSleep(); q.put(1); }).start();

ArrayList<Integer> ordered = new ArrayList<>(4);
for (int i = 0; i < 4; i++) {
    randomSleep();
    ordered.add(q.take());
}
System.out.println(ordered);

In this example, the order in which the main thread gets the offered values is quite random, which seems to defeat the purpose of a priority queue.在这个例子中,主线程获取提供的值的顺序是非常随机的,这似乎违背了优先级队列的目的。 Even with a single producer and single consumer, the order can not be ensured.即使是单一的生产者和单一的消费者,也无法保证顺序。

So, what is the use of PriorityBlockingQueue then?那么, PriorityBlockingQueue有什么用呢?

In this example, the order in which the main thread gets the offered values is quite random在这个例子中,主线程获取提供的值的顺序是非常随机的

Well you have a race-condition during the insertion and the retrieve of those elements.好吧,在插入和检索这些元素期间,您有一个竞争条件。 Hence, the reason why it looks random.因此,它看起来随机的原因。

Nonetheless, you could use for instance the PriorityBlockingQueue to sequentially field up with some elements (or tasks) that need to be pick up by multiple threads in parallel by their highest priority element/task .尽管如此,您可以使用例如PriorityBlockingQueue顺序排列一些元素(或任务),这些元素(或任务)需要由多个线程并行拾取,由它们的最高优先级元素/任务并行处理。 In such case you can take advantage of the thread-safe properties of a structure that guarantees you that the the highest priority element is always ordered first.在这种情况下,您可以利用结构的线程安全属性来保证最高优先级的元素始终排在第一位。

One example would be a Queue of tasks in which those tasks have a priority, and you want those same tasks to be processed in parallel.一个示例是任务队列,其中这些任务具有优先级,并且您希望并行处理这些相同的任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM