我想启动一个线程,并取消它,如果它未在5秒内完成:如何中断给定Future对象的线程?
private final class HelloWorker implements Callable<String> {
public String call() throws Exception {
while(true) {
if (Thread.isInterrupted()) {
return null;
}
}
return performExpensiveComputation();
}
private String performExpensiveComputation() {
// some blocking expensive computation that may or may not take a very long time
}
}
private ExecutorService executorService = Executors.newFixedThreadPool(threadPoolSize);
Future<String> future = executorService.submit(new HelloWorker());
try {
String s = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException e) {
future.cancel(true);
System.out.println("cancelled: " + future.isCancelled() + "done: " + future.isDone());
executorService.shutdown();
try {
System.out.println("try to terminate: " + executorService.awaitTermination(60, TimeUnit.SECONDS));
} catch (Exception ex) {
// ignore
}
}
但是它看起来像awaitTermination返回false。有没有办法让我来检查为什么ExecutorService不会终止?我能弄清楚哪些线程仍在运行?
'future.cancel(true)'实际上中断了线程。但是这只会打开'thread.isInterrupted()'标志。你将需要测试它或者介意你的'InterruptedException's。 – Gray
我可以通过任何方式调用thread.stop()? – Popcorn
'thread.stop()'已弃用。请参阅@ Marko的答案。 – Gray