[英]How to wait for all tasks in an ThreadPoolExecutor to finish without shutting down the Executor?
[英]Executor: Wait for specific tasks to finish
我正在運行的服務器應用程序獲得了多個我想要使用任務系統處理的任務請求。
每個任務都表示為一個Runnable
,將要求n
線程數從一個線程池,其中n
小於或等於到線程池的大小。 當然,線程池是必要的,以便不與CPU線程太多超載。
但是,其中一些任務可以是多線程的,有些則不能。 這就是為什么一個任務可能需要等待所有特定線程完成以便合並來自這些線程的結果以獲得最終結果。
如果一個人使用多個Thread
實例,可以加入這樣的:
try {
// Wait for all threads to finish their tasks
for (Thread thread : threads) {
thread.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
// Finish job here ..
但我需要使用java.util.concurrent.Executor
或任何與線程池一起使用的類似東西。
您可以為每個任務使用ExecutorService
和CyclicBarrier
,如下所示:
public class ThreadedTask implements Runnable {
CyclicBarrier barrier;
public ThreadedTask(CyclicBarrier barrier) {
this.barrier = barrier;
}
@Override
public void run() {
// do something
barrier.await();
}
}
ExecutorService executor = Executors.newFixedThreadPool(pool_size);
...
CyclicBarrier barrier = new CyclicBarrier(n+1);
for(int i=0; i<n; i++) {
// launch all tasks
executor.submit(new ThreadedTask(barrier));
}
// waits for the tasks to finish or timeout
barrier.await(seconds, TimeUnit.SECONDS);
如果我理解正確,你需要這樣的東西(但你的架構似乎太復雜了):
class MyTask implements Runnable {
@Override
public void run() {
// some work
}
}
之后:
ExecutorService executorService = Executors.newFixedThreadPool(2000);
ArrayList<Future> futures = new ArrayList<>();
futures.add(executorService.submit(new MyTask()));
futures.add(executorService.submit(new MyTask()));
futures.add(executorService.submit(new MyTask()));
for (Future future: futures) {
try {
future.get(100, TimeUnit.SECONDS);
} catch (Throwable cause) {
// process cause
}
}
每個future.get()將等待任務結束(在此示例中最多100秒)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.