在使用ExecutorService
和Future
对象(提交Runnable
任务)时,如果我给future的get函数指定了超时值,当抛出TimeoutException
时,底层线程会被终止吗?
在使用ExecutorService
和Future
对象(提交Runnable
任务)时,如果我给future的get函数指定了超时值,当抛出TimeoutException
时,底层线程会被终止吗?
它不会自动取消任务。除非您告诉它这样做。
例如,如果您等待一个可调用对象的结果20秒钟,但未获得结果,则表示您不再关心该结果。此时,您应该完全取消任务。
可以采用以下方式:
Future<?> future = service.submit(new MyCallable());
try {
future.get(100, TimeUnit.MILLISECONDS);
} catch (Exception e){
e.printStackTrace();
future.cancel(true); //this method will stop the running underlying task
}
不,它没有。而且甚至没有尝试中断任务。首先,Future.get与超时并没有这样说。其次,请尝试我的测试以了解它的行为
ExecutorService ex = Executors.newSingleThreadExecutor();
Future<?> f = ex.submit(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("finished");
}
});
f.get(1, TimeUnit.SECONDS);
1秒钟内打印
Exception in thread "main" java.util.concurrent.TimeoutException
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:228)
at java.util.concurrent.FutureTask.get(FutureTask.java:91)
at Test1.main(Test1.java:23)
再过1秒钟,任务将成功完成。
finished
Future
实现不支持。由于它是一个接口,我们不能对所有的Future
做出笼统的陈述。 - Duncan Jones Future<?> f = Executors.newSingleThreadExecutor().submit(() -> System.out.println("done"));
f.get(1, TimeUnit.SECONDS);
future.cancel(true);
并不能停止正在运行的底层任务,它只是将运行线程的中断标志设置为true。你的代码需要负责检查这个标志,如果为true则抛出InterruptedException。 - Thiago Kronig