使用Java ExecutorService,如何完成主動執行的任務,但是暫停處理等待任務?
我正在使用ExecutorService(ThreadPoolExecutor)執行(並排隊)很多工.我試圖寫一些儘可能優雅的關閉程式碼.
ExecutorService有兩種關閉方式:
>我可以呼叫ExecutorService.shutdown(),然後呼叫ExecutorService.awaitTermination(…).
>我可以呼叫ExecutorService.shutdownNow().
根據JavaDoc,關機命令:
Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
而shutdownNow命令:
Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
我想要這兩個選項之間的東西.
我想呼叫一個命令:
一個.完成當前活動的任務或任務(如關閉).
灣停止等待任務的處理(如shutdownNow).
例如:假設我有一個具有3個執行緒的ThreadPoolExecutor.它目前在佇列中有50個任務,前3個正在執行.我想允許這3個活動任務完成,但我不希望剩下的47個任務開始.
我相信我可以通過保留Future物件的列表,然後呼叫所有這些物件來關閉ExecutorService.但是由於任務正從多個執行緒提交給此ExecutorService,所以不會有一個乾淨的方式來執行此操作.
我真的希望我缺少一些明顯的東西,或者有一種乾淨的做法.
感謝任何幫助.
我最近遇到這個問題.可能有一個更優雅的方法,但是我的解決方案是首先呼叫shutdown(),然後拉出ThreadPoolExecutor使用的BlockingQueue,並呼叫clear()(或者將其釋放到另一個Collection進行儲存).最後,呼叫awaitTermination()可以讓執行緒池完成其板上的內容.
例如:
public static void shutdownPool(boolean awaitTermination) throws InterruptedException { //call shutdown to prevent new tasks from being submitted executor.shutdown(); //get a reference to the Queue final BlockingQueue<Runnable> blockingQueue = executor.getQueue(); //clear the Queue blockingQueue.clear(); //or else copy its contents here with a while loop and remove() //wait for active tasks to be completed if (awaitTermination) { executor.awaitTermination(SHUTDOWN_TIMEOUT, TimeUnit.SECONDS); } }
該方法將在引導類中使用引用執行程式包裝ThreadPoolExecutor來實現.
從ofollow,noindex" target="_blank">
ThreadPoolExecutor.getQueue()
javadoc中注意以下幾點很重要:
Access to the task queue is intended primarily for debugging andmonitoring. This queue may be in active use. Retrieving the task queuedoes not prevent queued tasks from executing.
這突出了事實,即在您消除BlockingQueue時,可能會呼叫其他任務.但是,根據that interface’s documentation ,所有BlockingQueue實現都是執行緒安全的,所以這不應該導致問題.
http://stackoverflow.com/questions/8158500/with-a-java-executorservice-how-do-i-complete-actively-executing-tasks-but-halt