我想啓動一個線程,並取消它,如果它未在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