我使用ExecutorService來簡化併發多線程程序。採取下面的代碼:ExecutorService,避免任務隊列變得太滿的標準方式
while(xxx)
ExecutorService exService = Executors.newFixedThreadPool(NUMBER_THREADS);
...
Future<..> ... = exService.submit(..);
...
}
在我的情況的問題是,提交()如果所有NUMBER_THREADS被佔用,不堵。結果是任務隊列被許多任務淹沒。這樣做的結果是,使用ExecutorService.shutdown()關閉執行服務需要很長時間(ExecutorService.isTerminated()將長時間爲false)。原因是任務隊列仍然很滿。
現在我的解決方法是用旗語合作,不允許有很多條目的ExecutorService的任務隊列中:
...
Semaphore semaphore=new Semaphore(NUMBER_THREADS);
while(xxx)
ExecutorService exService = Executors.newFixedThreadPool(NUMBER_THREADS);
...
semaphore.aquire();
// internally the task calls a finish callback, which invokes semaphore.release()
// -> now another task is added to queue
Future<..> ... = exService.submit(..);
...
}
我肯定有一個更好的多個封裝的解決方案?
我明白了。我在http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool%28int%29忽略了一個細節。在那裏提到,使用無界隊列作爲標準。 – 2010-02-11 21:37:03
我試過了。不幸的是,您的解決方案不會阻止(如我所願),但會拋出RejectedExecutionException。還發現:http://www.velocityreviews.com/forums/t389526-threadpoolexecutor-with-blocking-execute.html。所提出的解決方法似乎更復雜,因爲我的信號例子,該死! – 2010-02-11 23:53:22
由於RejectedExecutionException,如果隊列已滿,此工作不工作 – user249654 2012-05-21 12:51:51