博客
关于我
了解一下CompletionService的submit(Runnable task, V result)方法
阅读量:223 次
发布时间:2019-02-28

本文共 1181 字,大约阅读时间需要 3 分钟。

CompletionService 的示例演示

以下是一个使用 CompletionService 的 Java 代码示例,展示了如何为 Runnable 任务设置默认值返回。

public class CompletionServiceDemo {    public static void main(String[] args)            throws ExecutionException, InterruptedException {        ExecutorService pool = Executors.newFixedThreadPool(3);        ExecutorCompletionService
completionService = new ExecutorCompletionService<>(pool); Future
future = completionService.submit( new Runnable() { @Override public void run() { try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } }, "我是默认值" ); System.out.println(future.get()); pool.shutdown(); }}

运行结果

运行上述代码,您会看到以下结果:

我是默认值

总结

从运行结果可以看出,CompletionService 的主要作用是为 Runnable 类型的任务设置一个默认值返回。这使得在 futures 不完成之前,或者 future 失败时,可以立即获取一个预定义的默认值。

这种方式在那些任务可能需要等待后续操作完成(例如异步操作或阻塞操作)而无法立即返回结果的情况下非常有用。通过设置默认值,可以避免程序在等待 future 完成时陷入卡顿状态。

此外,CompletionService 还提供了许多有用的功能,例如处理多个 futures 的异常情况,以及在 futures 完成时进行后续处理。

转载地址:http://ljjp.baihongyu.com/

你可能感兴趣的文章
nft文件传输_利用remoting实现文件传输-.NET教程,远程及网络应用
查看>>
NFV商用可行新华三vBRAS方案实践验证
查看>>
ng build --aot --prod生成文件报错
查看>>
ng 指令的自定义、使用
查看>>
nghttp3使用指南
查看>>
Nginx
查看>>
nginx + etcd 动态负载均衡实践(三)—— 基于nginx-upsync-module实现
查看>>
nginx + etcd 动态负载均衡实践(二)—— 组件安装
查看>>
nginx + etcd 动态负载均衡实践(四)—— 基于confd实现
查看>>
Nginx + Spring Boot 实现负载均衡
查看>>
Nginx + uWSGI + Flask + Vhost
查看>>
Nginx - Header详解
查看>>
Nginx - 反向代理、负载均衡、动静分离、底层原理(案例实战分析)
查看>>
nginx 1.24.0 安装nginx最新稳定版
查看>>
nginx 301 永久重定向
查看>>
nginx css,js合并插件,淘宝nginx合并js,css插件
查看>>
Nginx gateway集群和动态网关
查看>>
Nginx Location配置总结
查看>>
Nginx log文件写入失败?log文件权限设置问题
查看>>
Nginx Lua install
查看>>