gpt4 book ai didi

java - FutureTask 似乎没有中断

转载 作者:行者123 更新时间:2023-11-29 07:49:52 24 4
gpt4 key购买 nike

我正在制作一些虚拟程序来了解这个 Java 类。我的定时任务调用了一个什么也不做的任务,在中断它之前给它 3 秒的时间。这是代码:

FutureTask<Integer> task = new FutureTask<>(new
Callable<Integer>(){
@Override
public Integer call() throws Exception {
int i =0;
while(i<100000){
;
}

return 0;
}

});

executor.execute(task);
try {
task.get(3000, TimeUnit.MILLISECONDS);
System.out.println("Everything was ok");
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException ex){
boolean result = task.cancel(true); //here i cancel the thread
System.out.println("the task has timed out "+result);
}

发生的情况是执行了 catch block ,但我的程序一直运行到线程完成为止。这就像 task.cancel 没有被接受。这是为什么?

最佳答案

您的任务受计算限制。它不执行任何 IO 或 hibernate ,此时 JVM 检查中断标志(任何抛出 InterruptedException 的方法)。因此,您的任务是不可中断的。

Interrupt 值得一读教程。注意:

What if a thread goes a long time without invoking a method that throws InterruptedException? Then it must periodically invoke Thread.interrupted, which returns true if an interrupt has been received. For example:

for (int i = 0; i < inputs.length; i++) {
heavyCrunch(inputs[i]);
if (Thread.interrupted()) {
// We've been interrupted: no more crunching.
return;
}
}

还有

The interrupt mechanism is implemented using an internal flag known as the interrupt status. Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static isInterrupted method, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.

请注意,人们经常会这样写:

 try {
// interruptible operation
}
catch (InterruptedException e) {
// do nothing
}

这不会重置中断标志。这导致不可中断的代码。参见 this JavaSpecialists newsletter了解更多信息

关于java - FutureTask 似乎没有中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22069325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com