如果您需要block-and-wait
,正如您所描述的,没有其他选择,但有类似的awaiCompletion()
实现。
您的循环方法可以改进。让我们ThreadPoolExecutor
作为一个例子。它有以下方法:
/**
* Blocks until all tasks have completed execution after a shutdown
* request, or the timeout occurs, or the current thread is
* interrupted, whichever happens first.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return {@code true} if this executor terminated and
* {@code false} if the timeout elapsed before termination
* @throws InterruptedException if interrupted while waiting
*/
boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;
这是实现:
public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException {
long nanos = unit.toNanos(timeout);
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
for (;;) {
if (runStateAtLeast(ctl.get(), TERMINATED))
return true;
if (nanos <= 0)
return false;
nanos = termination.awaitNanos(nanos);
}
} finally {
mainLock.unlock();
}
}
请注意:
- 无限循环应始终定义退出条件
- 在您的情况下,超时是必须的,因为您不太可能准备好无休止的等待
- 自然你必须知道是超时还是工作终止
所以,这是一个改编版本:
public static boolean awaitTermination(JobExecution execution, long timeout) throws InterruptedException {
final long limit = System.currentTimeMillis() + timeout;
for (;;) {
if (null != execution.getExitStatus()) {
return true;
}
if (System.currentTimeMillis() >= limit) {
return false;
}
Thread.sleep(timeout/10);
}
}