Java执行器:等待任务终止。 [英] Java executors: wait for task termination.

查看:219
本文介绍了Java执行器:等待任务终止。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要提交一些任务,然后等待他们,直到所有结果可用。每个向向量(默认情况下同步)添加 String 。然后我需要为Vector中的每个结果启动一个新任务,但是只有当所有先前的任务停止执行他们的工作时,我才需要这样做。

I need to submit a number of task and then wait for them until all results are available. Each of them adds a String to a Vector(that is synchronized by default). Then I need to start a new task for each result in the Vector but I need to do this only when all the previous tasks have stopped doing their job.

我想使用Java Executor,特别是我尝试使用 Executors.newFixedThreadPool(100)固定数量的线程(我有一个可变数量的任务可以是10或500),但我是新的执行者,我不知道如何等待任务终止。
这就像我的程序需要做的伪代码:

I want to use Java Executor, in particular I tried using Executors.newFixedThreadPool(100) in order to use a fixed number of thread (I have a variable number of task that can be 10 or 500) but I'm new with executors and I don't know how to wait for task termination. This is something like a pseudocode of what my program needs to do:

ExecutorService e = Executors.newFixedThreadPool(100);
while(true){

/*do something*/

for(...){
<start task>
}

<wait for all task termination>

for each String in result{
<start task>
}

<wait for all task termination>
}

我不能做一个e.shutdown, (true),我需要重用 executorService ...

I can't do a e.shutdown because I'm in a while(true) and I need to reuse the executorService...

你能帮我吗?你可以建议我一本关于java执行者的指南/书。

Can you help me? Can you suggest me a guide/book about java executors?

推荐答案

ExecutorService 给你一个机制来同时执行多个任务并获取 Future 对象的集合(表示任务的异步计算)。

The ExecutorService gives you a mechanism to execute multiple tasks simultaneously and get a collection of Future objects back (representing the asynchronous computation of the task).

Collection<Callable<?>> tasks = new LinkedList<Callable<?>>();
//populate tasks
for (Future<?> f : executorService.invokeAll(tasks)) { //invokeAll() blocks until ALL tasks submitted to executor complete
    f.get(); 
}



如果您有 Runnable s而不是 Callable ,您可以轻松地将 Runnable 变成 Callable< Object> ; 使用方法:

If you have Runnables instead of Callables, you can easily turn a Runnable into a Callable<Object> using the method:

Callable<?> c = Executors.callable(runnable);

这篇关于Java执行器:等待任务终止。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆