Я хочу, чтобы запустить поток и отменить его, если он не заканчивается в течение 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 возвращает ложь. Есть ли способ проверить, почему служба ExecutorService не будет завершена? Могу ли я выяснить, какие потоки еще запущены?
'future.cancel (true)' фактически прерывает поток. Но это только включает флаг 'thread.isInterrupted()'. Вам нужно будет протестировать его или вспомнить свое 'InterruptedException'. – Gray
в любом случае я могу назвать thread.stop()? – Popcorn
'thread.stop()' устарел. См. Ответ @ Марко. – Gray