還是有些疑問的
(1)內部實現原理
(2)入隊的時候需要不需要鎖住整個隊列?
public class PriorityBlockingQueueTest {<br />private static int COUNT = 100;<br />private static int THREAD_NUM = 10;</p><p>static class Producer extends Thread {<br />private BlockingQueue queue;<br />private Random rnd = new Random();</p><p>public Producer(BlockingQueue queue) {<br />this.queue = queue;<br />}</p><p>public void run() {<br />for (int i = 0; i < COUNT; i++) {</p><p>try {<br />int n = rnd.nextInt(COUNT);<br />queue.put(new Entity(n));<br />System.err.println("Producer.run()" + n);<br />} catch (InterruptedException e) {<br />e.printStackTrace();<br />}<br />}<br />}<br />}</p><p>static class Customer extends Thread {<br />private BlockingQueue queue;</p><p>public Customer(BlockingQueue queue) {<br />this.queue = queue;<br />}</p><p>public void run() {<br />for (int i = 0; i < COUNT; i++) {<br />try {<br />Entity e = (Entity) queue.take();<br />System.out.println("Customer.run()" + e.getSize());<br />} catch (InterruptedException e) {<br />e.printStackTrace();<br />}<br />}<br />}<br />}</p><p>static class Entity implements Comparable<Entity> {<br />private int size;</p><p>public Entity(int size) {<br />this.size = size;<br />}</p><p>public int getSize() {<br />return size;<br />}</p><p>public int compareTo(Entity o) {<br />return this.size > o.size ? 1 : ((this.size == o.size) ? 0 : -1);<br />}</p><p>}</p><p>private static PriorityBlockingQueue<Entity> queue = new PriorityBlockingQueue<Entity>();</p><p>public static long getQueuePerformanceTest(BlockingQueue queue,<br />int threadNum) throws InterruptedException {</p><p>long start = System.nanoTime();<br />Thread[] producers = new Producer[threadNum];<br />Thread[] customers = new Customer[threadNum];</p><p>for (int i = 0; i < threadNum; i++) {<br />producers[i] = new Producer(queue);<br />producers[i].start();<br />customers[i] = new Customer(queue);<br />customers[i].start();<br />}</p><p>for (int i = 0; i < threadNum; i++) {<br />producers[i].join();<br />customers[i].join();<br />}</p><p>long end = System.nanoTime();<br />return (end - start);<br />}</p><p>public static void main(String[] args) {<br />try {<br />getQueuePerformanceTest(queue, THREAD_NUM);<br />} catch (InterruptedException e) {<br />e.printStackTrace();<br />}<br />}<br />}