在等待 Executor 终止时如何避免子类化?
How can I avoid subclassing while waiting for an Executor to terminate?
我有一个 Executor
需要先终止才能关闭另一个 Executor
,我正在考虑尝试实施等待通知策略,但通知必须来自executor.isTerminated()
,所以除非我将它子类化,否则我无法通知关闭线程。是否有替代方法来对其进行子类化或旋转等待?
Executor executor = Executors.newFixedThreadPool(YOUR_THREAD_COUNT);
exector.shutDown();
boolean shutdown = false;
try {
shutdown = executor.awaitTermination(YOUR_TIME_OUT, TimeUnit.MILLISECOND);
} catch (InterruptedException e) {
// handle the exception your way
}
if (!shutdown) {
LOG.error("Executor not shut down before time out.");
}
我想您可能想要同步终止执行程序。我们总是可以使用变通方法来做到这一点:
//THE LOGIC BEFORE YOU WANT TO WAIT THE EXECUTOR
...
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
//THE LOGIC AFTER THE EXECUTOR TERMINATION
...
使用具有 MAX_VALUE 时间的 awaitTermination 方法。
我有一个 Executor
需要先终止才能关闭另一个 Executor
,我正在考虑尝试实施等待通知策略,但通知必须来自executor.isTerminated()
,所以除非我将它子类化,否则我无法通知关闭线程。是否有替代方法来对其进行子类化或旋转等待?
Executor executor = Executors.newFixedThreadPool(YOUR_THREAD_COUNT);
exector.shutDown();
boolean shutdown = false;
try {
shutdown = executor.awaitTermination(YOUR_TIME_OUT, TimeUnit.MILLISECOND);
} catch (InterruptedException e) {
// handle the exception your way
}
if (!shutdown) {
LOG.error("Executor not shut down before time out.");
}
我想您可能想要同步终止执行程序。我们总是可以使用变通方法来做到这一点:
//THE LOGIC BEFORE YOU WANT TO WAIT THE EXECUTOR
...
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
//THE LOGIC AFTER THE EXECUTOR TERMINATION
...
使用具有 MAX_VALUE 时间的 awaitTermination 方法。