Java如何使用PriorityBlockingQueue类?
本示例演示如何使用PriorityBlockingQueue该类。该PriorityBlockingQueue是一个实现BlockingQueue接口。这是一个无限制的并发队列。此类队列中的对象位置必须实现java.lang.Comparable接口。该Comparable接口定义此队列内元素的顺序优先级。
为简单起见,在此示例中,我们使用字符串对象作为要放入队列中的元素。本String类实现可比的接口。当我们运行此示例时,它将按字母顺序打印出字符串数组中的名称。
package org.nhooo.example.util.concurrent; import java.util.concurrent.BlockingQueue; import java.util.concurrent.PriorityBlockingQueue; public class PriorityBlockingQueueExample { public static void main(String[] args) { final String[] names = {"carol", "alice", "malory", "bob", "alex", "jacobs"}; final BlockingQueue<String> queue = new PriorityBlockingQueue<>(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < names.length; i++) { try { queue.put(names[i]); } catch (InterruptedException e) { e.printStackTrace(); } } } }, "Producer").start(); new Thread(new Runnable() { @Override public void run() { try { for (int i = 0; i < names.length; i++) { System.out.println(queue.take()); } } catch (InterruptedException e) { e.printStackTrace(); } } }, "Consumer").start(); } }
这段代码打印出来:
alex alice bob carol jacobs malory