我有一个运行几个线程的 ExecutorService。
我想要完成的是执行,然后等待所有线程终止。为了给您提供更多背景知识,每个 thread1
都连接到一个网站。
这是我想到的:
public static void terminateExecutor(ExecutorService taskExecutor) {
taskExecutor.shutdown();
try {
taskExecutor.awaitTermination(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
System.out.println("Some tasks were interrupted!"); //This gets printed
}
}
现在,奇怪的是,使用 ExecutorService 的主线程终止了,但其中的 thread1
却没有终止。
我注意到这一点是因为thread1
抛出了一个错误(此时主线程已经死了)告诉我它没有找到指定的URL(所以我猜这与连接有关) .
是否有可能 awaitTermination
不会终止 thread1
,因为它尝试(并且似乎正在重试)连接到无效链接?
我无法以任何其他方式停止thread1
(或者至少据我所知我不能),因为不存在任何类型的循环。
编辑:
我通过创建一个新类并将其提供给执行器来获取thread1
。
for (....)
{
String urlToVisit = globalUrl + links.get(i);
Thread thread1 = new MagicalThread(urlToVisit, 2).getThread();
executor.execute(thread1);
}
terminateExecutor(executor.getExecutor());
最佳答案
来自Javadoc (强调我的):
Blocks until all tasks have completed execution after a shutdown request
在调用awaitTermination
之前需要先调用shutdown()
,否则没有任何意义。
关于java - ExecutorService 未及时终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49480296/