问题描述
我想管理由TaskExecutor返回的Futures对象列表.
我有这样的东西
I want to manage a list of Futures objects returned by my TaskExecutor.
I've something like this
List<Future<String>> list
void process(ProcessThis processThis) {
for ( ...) {
Future<String> future = taskExecutor.submit(processThis);
list.add(future)
}
}
void removeFutures() {
for(Future future : list) {
assert future.cancel(true);
}
过程这是实现Callable<的任务. String>并检查Thread.interrupted()状态
ProcessThis is a task that implements Callable< String> and checks for Thread.interrupted() status
public String call() {
while (true) {
if (Thread.interrupted()) {
break;
}
doSomething();
}
}
现在的问题是,在调用Thread.interrupted()时,只有并发线程的一个子集返回"true".
removeFutures()中的assert对于每个被删除的将来都返回true(我也检查了isDone()和isCompleted().
被中断的线程数是随机的.超过15个正在运行的线程,有时13个被中断,有时2个...
我真的不明白问题出在哪里.如果我调用future.cancel(true)并返回true ...,然后检查Thread.interrupted(仅被调用一次),则我希望它也返回true.
对我想念的东西有任何想法吗?
我正在构建Java 1.6.0_02-b05
Now the problem is that only a subset of the concurrent Threads is returning 'true' when Thread.interrupted() is called.
The assert in removeFutures() returns true for every future that is removed (I checked isDone() and isCompleted() as well.
The number of Threads that are interrupted is random. Over 15 running Threads sometimes 13 are interrupted, sometimes 2 ...
I really don't understand where's the issue. if I call future.cancel(true) and this returns true... and then I check Thread.interrupted (this is called only once), I expect this to return true as well.
Any idea of what am I missing?
I'm on build java 1.6.0_02-b05
推荐答案
请注意,Thread.interrupted()
返回当前中断状态,然后将其清除,因此所有将来的调用都将返回false.您想要的可能是Thread.currentThread().isInterrupted()
.
Be aware that Thread.interrupted()
returns the current interrupted status and then clears it, so all future invocations will return false. What you want is probably Thread.currentThread().isInterrupted()
.
还要注意,future.cancel(true)
通常只会在任务已经完成或取消的情况下返回false.如果返回true,则不能保证该任务实际上将被取消.
Also be aware that future.cancel(true)
will usually only return false if the task had already been completed or canceled. If it returns true, that is no guarantee that the task will actually be canceled.
doSomething()
中发生了什么?由于中断,RuntimeException可能逃逸到某处.您是否设置了 UncaughtExceptionHandler ?如果不是,则需要传递 ThreadFactory 到Executor
,它将设置异常处理程序并记录所有错过的异常.
What is happening in doSomething()
? Its possible that a RuntimeException is escaping somewhere due to the interrupt. Do you have an UncaughtExceptionHandler set? If not, you'll need to pass a ThreadFactory to the Executor
that will set the exception handler and log any missed exceptions.
这篇关于Java线程-奇怪的Thread.interrupted()和future.cancel(true)行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!