3
这是一个非常简单的代码:FutureTask保持活跃
FutureTask<Integer> task = new FutureTask<>(new
Callable<Integer>(){
@Override
public Integer call() throws Exception {
int i =0;
while(i<10){
i++;
}
return 0;
}
});
计数10,然后退出......容易。
我执行这样的:
Executor executor = Executors.newCachedThreadPool();
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);
System.out.println("the task has timed out "+result);
}
我得到“一切正常”到控制台,因此任务正确执行并返回。 但是线程仍然存在!我可以通过在eclipse中执行它来看到它:标记正在执行的程序的红色方块仍处于活动状态。 但我的主要关闭后打印“一切正常”,所以它一定是那个任务。 为什么它不关闭?我怎样才能关闭它?
我看到一些ExecutorService类的例子,它有一个关闭方法,但我不想关闭整个线程池,因为我仍然需要它活动接受其他任务,我只想要关闭任务!