做了下实验,初步认为while(true)循环是属于无法被中断的那一类中的,如果没有while(true),则可以被canceljavadoc也对这种现象预留了解释空间:
Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason.从原理上讲,可能在某些不应该被中断的场合如果强行中断的话,会使某些对象或其它什么状态不一致,可能是出于这种担心吧~http://stackoverflow.com/questions/6969978/futuretask-cancel
Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason.从原理上讲,可能在某些不应该被中断的场合如果强行中断的话,会使某些对象或其它什么状态不一致,可能是出于这种担心吧~http://stackoverflow.com/questions/6969978/futuretask-cancel
while (true) {
System.out.println("test");
}
修改为
while (!Thread.currentThread().isInterrupted()) {
System.out.println("test");
}
谢谢指点,昨天后半夜的时候去stackoverflow也找到了这个关于cancel的解释,调用的是线程的interrupte();
但是现在的需求,线程中运行的是第三方代码,是不可控的,有可能里边有死循环,但是使用线程池又没有类似thread.stop的函数,请问有没有什么办法强制终止futureTask?
task中的代码是不可控的,已经用securitymanager限制了权限,但是还是没办法限制死循环能否强制终止task?
如果靠中断无法退出有没有强制中断task的方法???
我又做了2个实验:
如下代码可以终止,但是无法使用线程池
thread = new Thread(futureTask);
thread.start();try {
//exec.execute(thread);
thread.start();
result=task.get(timeLimit,TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
thread.stop();
}
如下代码使用了线程池,但是通过线程池执行以后,stop操作会失效:
thread = new Thread(futureTask);
exec.execute(thread);//exec是newSingleThreadExecutortry {
thread.start();
result=task.get(timeLimit,TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
thread.stop();
}
求指点,求解脱……
刚才回复错了人了,。。我又做了2个实验:
如下代码可以终止,但是无法使用线程池:
thread = new Thread(futureTask);
thread.start();try {
result=task.get(timeLimit,TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
thread.stop();
}
如下代码使用了线程池,但是通过线程池执行以后,stop操作会失效:thread = new Thread(futureTask);
exec.execute(thread);//exec是newSingleThreadExecutortry {
result=task.get(timeLimit,TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
thread.stop();
}
楼上刚贴的代码有误,重新贴一次
我知道stop有问题,,,但是不用stop真的没办法停止了。
而且现在stop对于线程池中的线程也无效。
有没有什么好点子指点一下?
通过线程池start的我明天有空看看源代码吧~
对于非妥善实现的线程而要强行终止的话可能也只有你所提到过的不计后果的stop方法了线程池中无法stop?没试过,觉得应该不存在区别才对或者存在换一种形式的相同实现,比如线程直接close之类。
我又做了2个实验:
如下代码可以终止,但是无法使用线程池
thread = new Thread(futureTask);
thread.start();try {
//exec.execute(thread);
thread.start();
result=task.get(timeLimit,TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
thread.stop();
}
如下代码使用了线程池,但是通过线程池执行以后,stop操作会失效:
thread = new Thread(futureTask);
exec.execute(thread);//exec是newSingleThreadExecutortry {
thread.start();
result=task.get(timeLimit,TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
thread.stop();
}
求指点,求解脱……
将线程池中thread.stop();改中Thread.currentThread().stop();试试!