java - JDK8的CompletableFuture使用问题
问题描述
CompletableFuture cf1 = CompletableFuture.supplyAsync(() -> { System.out.println('enter into completableFuture()'); try {TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) {e.printStackTrace(); } System.out.println('start to out of completableFuture()'); return 'a';});System.out.println('do something else');cf1.thenApply(v -> v + ' b').thenAcceptAsync(v ->System.out.println(v));System.out.println('finalize...');//注释最后一行,无法得到预期结果//TimeUnit.SECONDS.sleep(10);
得到引结果为:
do something elseenter into completableFuture()finalize...start to out of completableFuture()a b
以上代码如果注释掉最后一行,无法得到预期结果。
为什么一定要显式的让程序sleep10秒呢?
问题解答
回答1:见CompletableFuture.supplyAsync的javadoc:
Returns a new CompletableFuture that is asynchronously completed by a task running in the ForkJoinPool.commonPool() with the value obtained by calling the given Supplier.
而ForkJoinPool.commonPool()的javadoc:
Returns the common pool instance. This pool is statically constructed; its run state is unaffected by attempts to shutdown or shutdownNow. However this pool and any ongoing processing are automatically terminated upon program System.exit. Any program that relies on asynchronous task processing to complete before program termination should invoke commonPool().awaitQuiescence, before exit.
如果你把最后的sleep改成ForkJoinPool.commonPool().awaitQuiescence(2, TimeUnit.SECONDS);也能达到你预期结果
回答2:搜索一下:守护线程当线程中只剩下守护线程时JVM就会退出,反之还有任意一个用户线程在,JVM都不会退出。我们可以猜测CompletableFuture.supplyAsync启动了一个守护线程,实际上CompletableFuture内部默认使用ForkJoinPool,该线程池初始化一个线程工厂类:
defaultForkJoinWorkerThreadFactory = new DefaultForkJoinWorkerThreadFactory();
查看他的的实现,每次都是创建守护进程。至于为什么一定要主线程sleep就很好理解。
相关文章:
1. javascript - 项目用IE浏览器打开修改前端内容,后台数据修改了,但是前端页面内容不变,用谷歌浏览器测试前端页面可以刷新,求大神解决。2. docker-compose中volumes的问题3. macos - mac下docker如何设置代理4. docker-compose 为何找不到配置文件?5. 为什么要使用javascript函数包装器(添加在coffeescript中)“。call(this)”6. docker网络端口映射,没有方便点的操作方法么?7. angular.js - $emit(,)的具体意思是什么作用呢?8. python - Fiddler+Android模拟器抓取app,json数据被加密了,如何解析?9. css3 - div中的div无法控制高度?我想控制右边几个蓝色div的高度10. MySQL的SELECT...FOR UPDATE究竟起什么作用

网公网安备