【发布时间】:2019-08-28 20:55:48
【问题描述】:
我正在寻找使线程执行超时的方法,并找到以下示例:https://stackoverflow.com/a/16231834/10015830
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 被阻塞。换句话说,我不需要得到我的可调用结果。因为在我的实际应用程序中,父线程是定期执行的(scheduled 任务,比如说,定期 5 秒)。
有没有办法在不使用future.get 且不阻塞父线程的情况下使线程超时? (看来invokeAll 也被屏蔽了)。
【问题讨论】:
-
线程超时是什么意思?如果任务未完成,您只想在 100 毫秒后取消它?
-
@SotiriosDelimanolis 到
cancel一个任务,从哪里来?父线程可能已经终止。是否可以从子线程中自动取消?
标签: java multithreading