【发布时间】:2022-11-05 00:41:49
【问题描述】:
我对 Java 编程相当陌生,并且被提示进行一些重构,其中该代码的逻辑是相同的,只需要放入一个可以调用的方法中,并将服务作为参数传递。该功能基本上是关闭线程,我们这里有两个线程池,只需要知道如何将这些服务作为参数传递,它们也是接口的一部分。这是我试图重构为可以调用的方法的代码。
if (scheduledExecutorService1 != null) {
scheduledExecutorService1.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!scheduledExecutorService1.awaitTermination(60, TimeUnit.SECONDS)) {
scheduledExecutorService1.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!scheduledExecutorService1.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
scheduledExecutorService1.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
if (scheduledExecutorService2 != null) {
scheduledExecutorService2.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!scheduledExecutorService2.awaitTermination(60, TimeUnit.SECONDS)) {
scheduledExecutorService2.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!scheduledExecutorService2.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
scheduledExecutorService2.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
【问题讨论】:
-
最好在Code Review 询问有关优化运行代码的问题