【发布时间】:2019-05-21 07:54:49
【问题描述】:
我把workstealingpool的大小设置为1,看来future.get()并没有阻塞线程。
@Test
public void runAsyncThenApplyExample() {
ExecutorService executor = Executors.newWorkStealingPool(1);
CompletableFuture cf = CompletableFuture.supplyAsync(
() -> {
//assertTrue(Thread.currentThread().isDaemon());
System.out.println("func: " + threadName());
Callable<Long> callable = () ->stub();
Future<Long> future = executor.submit(callable);
try {
future.get(); <<<<< **I think this should block the thread**
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return 1;
}, executor).thenAccept(s -> {
System.out.println("accept: " + threadName());
});
//assertFalse(cf.isDone());
System.out.println("main: " + threadName());
sleep(10);
assertTrue(cf.isDone());
}
private Long stub() {
System.out.println("stub: " + threadName());
return 1L;
}
private String threadName() {
return Thread.currentThread().getName();
}
输出:
函数:ForkJoinPool-1-worker-3
主要:主要
存根:ForkJoinPool-1-worker-3
接受:ForkJoinPool-1-worker-3
【问题讨论】:
-
好吧,它会一直阻塞,直到您的
stub返回,但这是超快的,所以您不会注意到它。 -
如果阻塞,为什么get线程和stub线程一样。
标签: java concurrency block future forkjoinpool