未来超时杀死线程执行 [英] Does a Future timeout kill the Thread execution

查看:170
本文介绍了未来超时杀死线程执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 ExecutorService 未来对象时(提交 Runnable tasks),如果我为未来的get函数指定一个超时值,当抛出 TimeoutException 时底层线程是否被杀死?

When using an ExecutorService and Future objects (when submitting Runnable tasks), if I specify a timeout value to the future's get function, does the underlying thread get killed when a TimeoutException is thrown?

推荐答案

没有。为什么呢?除非你告诉它。

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

例如,在Callable的情况下,这里有一个非常有效的问题。如果你等待结果说20秒,你没有得到它,那么你对结果不感兴趣了。

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.

这样的东西:

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
    }

这篇关于未来超时杀死线程执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆