我正在制作一些虚拟程序来了解这个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块被执行,但我的程序一直运行直到线程完成。就像task.cancel没有被接受一样。为什么会这样呢?
发布于 2014-02-27 13:02:53
你的任务是计算机约束的.它不执行任何IO或睡眠,这是JVM检查中断标志(任何抛出InterruptedException的方法)的时候。因此,你的任务是不间断的。
值得一读中断教程。注意:
如果线程运行很长时间而不调用抛出InterruptedException的方法,怎么办?然后,它必须定期调用Thread.interrupted,如果接收到中断,则返回true。例如:
for (int i = 0; i < inputs.length; i++) {
heavyCrunch(inputs[i]);
if (Thread.interrupted()) {
// We've been interrupted: no more crunching.
return;
}
}而且还
中断机制是使用称为中断状态的内部标志来实现的。调用Thread.interrupt设置此标志。当线程通过调用静态方法Thread.interrupted来检查中断时,中断状态将被清除。一个线程用于查询另一个线程的中断状态的非静态isInterrupted方法不会更改中断状态标志。
请注意,人们经常会写以下这样的东西:
try {
// interruptible operation
}
catch (InterruptedException e) {
// do nothing
}不会重置被中断的标志。这将导致不间断代码。有关更多信息,请参见这是JavaSpecialists通讯
https://stackoverflow.com/questions/22069325
复制相似问题