【问题标题】:Limit time on a functioncall [duplicate]限制函数调用的时间[重复]
【发布时间】:2012-09-01 12:07:43
【问题描述】:

可能重复:
How to timeout a thread

我正在使用函数调用在树中进行递归搜索。它在类变量中设置最佳答案,并且函数本身不返回任何内容。

所以我想限制函数的允许时间。如果时间用完了,它就会停止并且线程被销毁。如果我想将通话限制在两秒内怎么办:

runFunction(search(),2000);

【问题讨论】:

标签: java multithreading time depth-first-search


【解决方案1】:

假设您使用的是 Java 5 或更高版本,我将使用 ExecutorService 接口和提交方法:

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<?> future = executor.submit(new Runnable() {

@Override
public void run() {
    search();
    }
});
try {
    future.get(2000, TimeUnit.SECONDS);
} catch (TimeoutException e) {
    // handle time expired
}

使用此方法,您还可以通过提交 Callable 而不是 Runnable 来调整线程以返回值。

【讨论】:

  • 只有在search 是可中断的情况下才有效。
  • 完美!我需要销毁线程还是自动完成?
猜你喜欢
  • 2020-10-07
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多