簡體   English   中英

Java最佳隊列使用者實現

[英]Best Queue Consumer implementation in Java

美好的一天!

我想讓ExecutorService使用者從隊列中獲取數據並在服務器端使用它。 這個想法是-我不時輪詢隊列,如果我發現隊列不為空,則使用N個線程(讓我說5個)啟動ExecutorService。 然后我w8而隊列將為空並關閉線程。 再說一遍-輪詢隊列中的數據...。 還是可能有一些准備就緒的實現/框架來完成此類任務?

我發現了ConcurrentQueue cunsumers的此實現:

public class ConcurrentQueueClient implements Runnable {

    private Queue<String> concurrentQueue;

    public ConcurrentQueueClient(Queue concurrentQueue) {
        this.concurrentQueue = concurrentQueue;
     }

    public void run() {
         boolean stopCondition = (concurrentQueue.size() == 0);

        while (!stopCondition) {
            for (int i = 0; i < concurrentQueue.size(); i++) {
                System.out.println("Client dequeue item "
                        + concurrentQueue.poll());

            }
            stopCondition = (concurrentQueue.size() == 0);
        }

        System.out.println("Client thread exiting...");
    }
 }

並以這種方式進行測試:

 Queue<String> queue = new ConcurrentLinkedQueue<String>();
 ExecutorService consumers = null;
 while(true) {

if(queue.size() != 0) {
   consumers = Executors.newFixedThreadPool(100);
   for (int i = 0; i < 5; i++) {
        ConcurrentQueueClient client = new ConcurrentQueueClient(queue);
        consumers.execute(client);
   }
}

while (queue.size() != 0) {
       try {
           Thread.sleep(1500);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }

}

 consumers.shutdown();
 try {
     consumers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
 } catch (InterruptedException e) {
     e.printStackTrace();
 }


}

重來。 將字符串包裝成可調用或可運行的字符串,然后將它們排隊到執行程序服務中。

如果您要處理的數據有限,那么可以像以前一樣讓主線程調用consumer.shutdown()和consumer.awaitTermination(...),但是沒有睡眠循環。 如果您要從隊列中無限期地進行處理,則在服務停止之前,不執行shutdown()。

如果沒有有限的阻塞隊列(什么也不會阻塞queue.put()),您也會遇到內存問題。 可以在創建時將ArrayBlockingQueue賦予執行者服務(請參閱ThreadPoolExecutor(...))

執行器服務的線程正在按照設計檢查(queue.take())任務隊列。 嘗試避免輪詢,這會浪費CPU。 始終嘗試在reentrantlocks的條件下等待/通知(或等待/發出信號)(執行程序服務代碼中的所有內容都由您來處理)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM