如果为不同的作业嵌套了Future
,并且两个Future
都具有相同的超时,则主Future
不会被取消。但是,如果子级Future
的超时时间小于主要的Future
,则可以取消超时。
这是什么原因?
我的例子:
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
Future<Object> main= service.submit(()->{
Future<Object> child= service.submit(()->{
while(!Thread.currentThread().isInterrupted()){
System.out.println("child future is running...");
Thread.sleep(100);
}
return 0;
});
try{
child.get(10,TimeUnit.MILLISECONDS);
}catch(Exception we){
System.out.println("child future cancelled.");
child.cancel(true);
}
while(!Thread.currentThread().isInterrupted()){
System.out.println("main future is running...");
Thread.sleep(100);
}
return 0;
});
try{
main.get(10,TimeUnit.MILLISECONDS);
}catch(Exception we){
System.out.println("main future cancelled.");
main.cancel(true);
}
}