在 Java 中关闭 ExecutorService 时显示友好消息?
Display friendly message when ExecutorService is shutting down in Java?
所以,我在 Java 中有一个关闭执行程序服务的代码,如下 -
public void shutdownExecutor() {
executor.shutdown();
try {
executor.awaitTermination(requestInfo.getUploadThreadCount() * 30,
TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.error(e);
}
}
在上面的代码中,如您所见,客户端应用程序(控制台或 Web)变为空白,直到线程数 * 30 秒 运行 结束。如何在此处显示友好消息?
例如,我已将执行程序阻止 10 秒以进行测试。
ExecutorService executor = Executors.newFixedThreadPool(4);
executor.submit(() -> {
try {
Thread.sleep(10_000);
} catch (Exception e) {
e.printStackTrace();
}
});
executor.shutdown();
System.out.println("The executor is shutting down, "+
"why not make yourself a cup of tea whilst you wait?");
try {
executor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.error(e);
}
如果你的意思是你想在等待时显示一条周期性消息,你可以这样做(例如,每 1 秒显示一条消息,最多 30 秒):
try {
long endTime = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
while (true) {
long timeout = Math.min(
TimeUnit.SECONDS.toNanos(1), endTime - System.nanoTime());
if (timeout <= 0
|| executor.awaitTermination(timeout, TimeUnit.NANOSECONDS)) {
break;
}
System.err.println("Still waiting for timeout");
}
} catch (InterruptedException e) {
logger.error(e);
Thread.currentThread().interrupt();
}
所以,我在 Java 中有一个关闭执行程序服务的代码,如下 -
public void shutdownExecutor() {
executor.shutdown();
try {
executor.awaitTermination(requestInfo.getUploadThreadCount() * 30,
TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.error(e);
}
}
在上面的代码中,如您所见,客户端应用程序(控制台或 Web)变为空白,直到线程数 * 30 秒 运行 结束。如何在此处显示友好消息?
例如,我已将执行程序阻止 10 秒以进行测试。
ExecutorService executor = Executors.newFixedThreadPool(4);
executor.submit(() -> {
try {
Thread.sleep(10_000);
} catch (Exception e) {
e.printStackTrace();
}
});
executor.shutdown();
System.out.println("The executor is shutting down, "+
"why not make yourself a cup of tea whilst you wait?");
try {
executor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.error(e);
}
如果你的意思是你想在等待时显示一条周期性消息,你可以这样做(例如,每 1 秒显示一条消息,最多 30 秒):
try {
long endTime = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
while (true) {
long timeout = Math.min(
TimeUnit.SECONDS.toNanos(1), endTime - System.nanoTime());
if (timeout <= 0
|| executor.awaitTermination(timeout, TimeUnit.NANOSECONDS)) {
break;
}
System.err.println("Still waiting for timeout");
}
} catch (InterruptedException e) {
logger.error(e);
Thread.currentThread().interrupt();
}