简体   繁体   中英

How can I use ExecutorService to get results of all the tasks submitted?

I have a requirement where I have to launch 5 threads for 5 tasks and there's a specific timeout for the task to be completed. After timeout I want the results of all the tasks. How can I use ExecutorService for this ? From what I have read about ExecutorService I concluded I needed something along the lines of :

List<Future> futures = new ArrayList<Future>();
futures.addAll(executor.submit(new someCallable()));
try {
    if (!executorService.awaitTermination(30*1000, TimeUnit.MILLISECONDS)) {
        executorService.shutdownNow();
    } 
} catch (InterruptedException e) {
    executorService.shutdownNow();
}

Should I do a future.get() ? What about the interrupted/incomplete threads' result ? I am confused with this part. In case of failed threads I want to mark their status field=Failed, in case of successful threads, I want to mark them as success.

您可以在指定的超时时间内仅使用ExecutorService invokeAll - API

After timeout I want the results of all the tasks. How can I use ExecutorService for this ?

I would suggest to use Callable

A task that returns a result and may throw an exception . Implementors define a single method with no arguments called call.

So, when you override call method either you return some status or just throw exception case of failure. Then, later using

future.get()

loop through all your submitted tasks and get their status and accordingly you can update status for further processing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM