【发布时间】:2015-08-31 09:56:07
【问题描述】:
我有以下课程:
public class Service{
private static final ExecutorService executor = Executors.newFixedThreadPool(4);
public synchronized void execute(Collection<Runnable> runs){
for(Runnable r: runs){
executor.execute(r);
}
}
public boolean isComplete(){
//should return true iff all tasks applied by the execute(Collection<Runnable> runs)
//method're finished their execution (normally or abruptly,
//it doesn matter)
}
}
如何实现isComplete() 方法。我需要检查是否有当前正在进行的任务。如果执行器被清除(所有任务都完成),那么方法应该返回true,否则返回false。
【问题讨论】:
-
在您的代码示例中,
execute是否同步? -
@AndyBrown 在我提供的代码中,没有。但我打算按以下方式使用它:一旦执行器开始执行任务,任何其他线程都不可能调用执行方法,直到所有
Runnables 完成。 -
这意味着您可以重新使用
Service。我很想不这样做,因为它是如此轻量级 - 只是让它只允许单次提交,然后在完成后被丢弃。否则,您将获得不完整的服务,然后是完整的,然后是不完整的...... - 这可能会导致问题。 -
@AndyBrown 事情是
Service有Application Scope,所以我不认为我会以不完整的服务告终...... -
我有强烈的感觉,你正在重塑
invokeAll...
标签: java multithreading threadpoolexecutor