老师,想问下关于future cancle方法
来源:1-1 本课程介绍

奶茶三兄弟d
2021-11-17
@RestController
@RequestMapping("/test/")
public class TestController {
@GetMapping("supply")
@ResponseBody
public Integer supply() throws ExecutionException, InterruptedException {
List<CompletableFuture<Integer>> list = new ArrayList<>();
for (int i = 1; i < 6; i++) {
int finalI = i;
CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(finalI * 2000);
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
return finalI;
}
return finalI;
});
list.add(integerCompletableFuture);
}
Integer i = 0;
for (CompletableFuture<Integer> integerCompletableFuture : list) {
if (i >= 2) {
boolean cancel = integerCompletableFuture.cancel(true);
System.out.println(cancel);
}else {
i += integerCompletableFuture.get();
}
}
System.out.println(i);
return i;
}
}
这是上面这段代码的执行结果:
ForkJoinPool.commonPool-worker-1
ForkJoinPool.commonPool-worker-2
ForkJoinPool.commonPool-worker-3
true
true
true
3
ForkJoinPool.commonPool-worker-4
ForkJoinPool.commonPool-worker-1
ForkJoinPool.commonPool-worker-5
老师,这个我很疑惑,明明已经取消了3个线程执行,cancle方法也返回了3次true,为啥之后被取消的线程 还继续执行。。打印出来线程名称。
写回答
1回答
-
我的运行结果并没打印出后面的线程名称:
ForkJoinPool.commonPool-worker-9
ForkJoinPool.commonPool-worker-2
true
true
true
3
152021-11-18
相似问题
生产者消费者问题的理解
回答 1
关于wait方法
回答 1