我想在5秒后取消我的两项任务,但下面的代码不起作用。出于某种原因,如果我不提交这两项任务并注释掉取消命令,我会得到#34;程序已经完成......" 5secs后印刷线。如果我提交上述两个任务,那么该行永远不会被打印出来,任务就会永远继续下去。
ScheduledExecutorService exec = (ScheduledExecutorService) Executors.newScheduledThreadPool(2);
Future<?> res1 = exec.submit(p);
Future<?> res2 = exec.submit(c);
exec.schedule(new Runnable(){
public void run(){
res1.cancel(true);
res2.cancel(true);
System.out.println("Program has finished execution after 5s.");
}
}, 5, TimeUnit.SECONDS);
//task code
public void run() {
while(true){
if (Thread.currentThread().isInterrupted()) return;
try{
//do stuff
...
System.out.println("Doing stuff");
}
catch (InterruptedException e){
e.printStackTrace();
return;
}
}
}
我也尝试了exec.awaitTermination,但它没有用。