Java Future 超时是否会终止线程执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16231508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:54:23  来源:igfitidea点击:

Does a Future timeout kill the Thread execution

javaconcurrencyexecutorservicefuture

提问by Nico Huysamen

When using an ExecutorServiceand Futureobjects (when submitting Runnabletasks), if I specify a timeout value to the future's get function, does the underlying thread get killed when a TimeoutExceptionis thrown?

使用ExecutorServiceandFuture对象时(提交Runnable任务时),如果我为未来的 get 函数指定超时值,那么在TimeoutException抛出a 时底层线程是否会被杀死?

采纳答案by Eugene

It does not. Why would it? Unless you tell it to.

它不是。为什么会呢?除非你告诉它。

There is a very valid concern here in case of a Callable for example. If you waited for the result for say 20 seconds and you did not get it, then you are not interested in the result anymore. At that time you should cancel the task at all.

例如,在 Callable 的情况下,这里有一个非常有效的问题。如果您等了 20 秒后没有得到结果,那么您就不再对结果感兴趣了。那时你应该完全取消任务。

Something like this:

像这样的东西:

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
    }

回答by Evgeniy Dorofeev

No it doesnt. Morover there is even no attempt to interrupted the task. First of all Future.get with timeout doesn't say so. Secondly, try my test to see how it behaves

不,它没有。Morover甚至没有试图打断任务。首先 Future.get with timeout 没有这么说。其次,尝试我的测试,看看它的行为

    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);

in 1 sec it prints

在 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)

after another 1 sec the task successfullt finishes

再过 1 秒后,任务成功完成

finished

回答by gurvinder372