nan*_*no7 2 java multithreading timeout callable executorservice
我在Java中使用ExecutorService,我注意到了一个我不理解的行为.我使用Callable,当我调用我的线程(实现Callable的类)时,我设置了一个超时.然后我等待结果,future.get()之后我想检查future.isDone()执行任务期间是否发生超时.
正如我在有关超时的invokeAll文档中所读到的那样: returns a list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list. If the operation did not time out, each task will have completed. If it did time out, some of these tasks will not have completed.
所以我想我会在两种情况下获得Future结果列表,如果发生超时,如果没有.
现在发生的事情如下:当发生超时时,代码不会继续future.get(),我没有达到可以检查是否发生超时的程度future.isDone().我没有发现任何异常,我直接导致我的代码中的finally块,我真的不明白.
这是我的代码片段:
try {
// start all Threads
results = pool.invokeAll(threads, 3, TimeUnit.SECONDS);
for (Future<String> future : results)
{
try
{
// this method blocks until it receives the result, unless there is a
// timeout set.
final String rs = future.get();
if (future.isDone())
{
// if future.isDone() = true, a timeout did not occur.
// do something
}
else
{
// timeout
// log it and do something
break;
}
}
catch (ExecutionException e)
{
// log messages and break, this is a snippet!
}
catch (InterruptedException ex)
{
// log message and break, this is a snippet!
}
}
}
catch (InterruptedException ex)
{
// log message, this is a snippet!
}
finally
{
// when a timeout occurs, the code jumps from future.get() directly to this point!
}
Run Code Online (Sandbox Code Playgroud)
可能有人解释我,为什么我无法达到future.isDone()以及我应该改变什么才能识别超时?
谢谢!
| 归档时间: |
|
| 查看次数: |
5167 次 |
| 最近记录: |