PriorityBlockingQueue 的一個例子

來源:互聯網
上載者:User

還是有些疑問的

(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 />}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.