我需要提交一些任务,然后等待他们,直到所有的结果都可用。它们中的每一个都会向Vector添加一个String (默认情况下是同步的)。然后,我需要为Vector中的每个结果启动一个新任务,但只有当所有以前的任务都停止执行其工作时,我才需要这样做。
我想使用Java,特别是为了使用固定数量的线程,我尝试过使用Executors.newFixedThreadPool(100) (我有一个可变数量的任务,可以是10或500),但我是执行器的新手,我不知道如何等待任务终止。这是我的程序需要做的事情的伪代码:
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,因为我在一段时间内(真的),我需要重用executorService...
你能帮帮我吗?你能给我推荐一本关于java执行器的指南/书吗?
发布于 2009-08-24 12:48:05
ExecutorService为您提供了一种同时执行多个任务并获取Future对象集合(表示任务的异步计算)的机制。
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();
}如果您使用的是Runnables而不是Callables,则可以使用以下方法轻松地将Runnable转换为Callable<Object>:
Callable<?> c = Executors.callable(runnable);发布于 2009-08-24 12:52:44
你能给我推荐一本关于java执行器的指南/书吗??
我可以回答这一部分:
Brian Goetz的 (与Tim Peierls,Joshua Bloch,Joseph Bowbeer,David Holmes和Doug Lea)最有可能是你最好的选择。

不过,它不仅涉及执行器,还涵盖了java.util.concurrent包的一般内容,以及基本的并发概念和技术,以及一些高级主题,如Java内存模型。
发布于 2009-08-24 13:03:15
与其直接将Runnable或Callable提交给Executor并存储相应的Future返回值,我建议使用CompletionService实现在完成Future时检索每个。这种方法将任务的产生与已完成任务的消耗解耦,例如允许在一段时间内在生产者线程上产生新任务。
Collection<Callable<Result>> workItems = ...
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletionService<Result> compService = new ExecutorCompletionService<Result>(executor);
// Add work items to Executor.
for (Callable<Result> workItem : workItems) {
compService.submit(workItem);
}
// Consume results as they complete (this would typically occur on a different thread).
for (int i=0; i<workItems.size(); ++i) {
Future<Result> fut = compService.take(); // Will block until a result is available.
Result result = fut.get(); // Extract result; this will not block.
}https://stackoverflow.com/questions/1322147
复制相似问题