在Java中ExecutorService关闭时显示友好消息?
所以,我有一个代码,用于关闭Java中的executor服务,如下所示-在Java中ExecutorService关闭时显示友好消息?,java,multithreading,threadpool,executorservice,Java,Multithreading,Threadpool,Executorservice,所以,我有一个代码,用于关闭Java中的executor服务,如下所示- public void shutdownExecutor() { executor.shutdown(); try { executor.awaitTermination(requestInfo.getUploadThreadCount() * 30, TimeUnit.SECONDS); } catch (InterruptedException e
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);
}
例如,我已阻止执行器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秒):
试试看{
long endTime=System.nanoTime()+TimeUnit.SECONDS.toNanos(30);
while(true){
长超时=Math.min(
TimeUnit.SECONDS.toNanos(1),endTime-System.nanoTime();
如果(timeout如果您的意思是希望在等待时显示定期消息,您可以这样做(例如,每1秒显示一条消息,最多30秒):
试试看{
long endTime=System.nanoTime()+TimeUnit.SECONDS.toNanos(30);
while(true){
长超时=Math.min(
TimeUnit.SECONDS.toNanos(1),endTime-System.nanoTime();
如果(超时添加System.out.println(“友好消息”);
在调用waittermination
?(不清楚需要消息“友好”的含义)在调用waittermination
之前添加System.out.println(“友好消息”);
?(不清楚你需要什么样的信息才能“友好”)