public class CompletableServiceTest { 

    public static void main(String[] args) throws ExecutionException, InterruptedException {

//      test1();

//      test2();

        test3();
} //这种方式提交的任务,有可能任务A是第一个执行完的,但是返回的顺序却不是第一个
public static void test1() throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool();
List<Callable> task = IntStream.range(, ).boxed().map(CompletableServiceTest::toTask).collect(Collectors.toList());
List<Future<String>> futures = new ArrayList<>();
task.forEach(r -> futures.add(executorService.submit(r))); System.out.println(futures.get().get());
System.out.println("======4======"); System.out.println(futures.get().get());
System.out.println("======3======");
} //这种方式可以保证假如任务A是第一个执行完的,那么他也是第一个返回的
public static void test2() throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool();
List<Callable> task = IntStream.range(, ).boxed().map(CompletableServiceTest::toTask).collect(Collectors.toList());
CompletionService completionService = new ExecutorCompletionService(executorService);
task.forEach(r -> completionService.submit(r));
Future<?> future = null;
while ((future = completionService.take()) != null){
System.out.println(future.get());
} } //由于调用线程池的shutdownNow方法,可能正在执行的任务被中断后,任务的状态丢失。该任务不包含在shutdownNow的返回值中
//解决的办法是在任务里定义一个状态,表示是否完成
public static void test3() throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool();
List<Callable> task = IntStream.range(, ).boxed().map(MyTask::new).collect(Collectors.toList());
task.forEach(r -> executorService.submit(r));
TimeUnit.SECONDS.sleep();
executorService.shutdownNow(); //这里虽然返回了未执行完的任务,但是不可性
//由于调用shutdownNow方法,任务被中断没有成功执行完的任务
task.stream().filter(c-> !((MyTask)c).isSuccess()).forEach(c->{System.out.println("task value : " +((MyTask) c).value);}); } public static class MyTask implements Callable<String>{
private final Integer value;
private boolean success = false;
MyTask(int value){
this.value = value;
} @Override
public String call() throws Exception {
System.out.println("task [" + value +"] will be executed");
TimeUnit.SECONDS.sleep(value*+);
System.out.println("task [" + value +"] executes done");
success = true;
return "task result - "+ value;
} public boolean isSuccess(){
return success;
}
} private static Callable<String> toTask(int i){
return ( ) ->{
try {
System.out.println("task [" + i +"] will be executed");
TimeUnit.SECONDS.sleep(i*+);
System.out.println("task [" + i +"] executes done");
return "task result - "+ i;
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}; }
}

CompletableService的更多相关文章

随机推荐

  1. 爬取bilibili首页菜单获取li内容

    代码: import requests from bs4 import BeautifulSoup def html_save(s): with open('哔哩哔哩.csv','a')as f: f ...

  2. 【LeetCode】2. 两数相加

    题目 给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字.   如果,我们将这两个数相加起来,则会返回一个新的链表来表 ...

  3. 基于swoole实现多人聊天室

    核心的swoole代码 基本的cs(client-sercer)结构不变,这里利用的是redis的哈希和set来储存和分组;从而达到了分组,统计,定时推送等功能;最后利用onclose事件来剔除断开的 ...

  4. Shell(三):echo、printf、test命令

    一.echo 1.显示普通字符串: echo "today is a wonderful day" 这里的双引号可以省略. 2.显示转义字符: echo "\" ...

  5. Add a Class from the Business Class Library 从业务类库添加类 (XPO)

    In this lesson, you will learn how to use business classes from the Business Class Library as is. Fo ...

  6. 1G内存VPS安装 mysql5.6 经常挂

    背景介绍 去年3月份的时候参加了腾讯云主机活动,5年362,非常优惠.当时的想法是买来可以瞎整一波,虽然配置不高,但是搞点事情也够用. 配置如下,上海机房 1 核 1 GB 1 Mbps 系统盘:普通 ...

  7. vue学习笔记(一): 建立 vue-cli 初始网站

    在安装vue-cli之前,要先安装node.js这个大家百度一下就可以了 1.安装 vue-cli npm install -g @vue/cli-init 2.初始化一个项目,名为 hcmanage ...

  8. 交互式shell脚本web console

    官网:http://web-console.org/ 这个脚本可以实现web下交互,也就是有了这玩意后可以不用反弹shell了. <?php // Web Console v0.9.7 (201 ...

  9. Wireshark使用教程:不同报文颜色的含义

    - 设置 色彩规则有两个入口,一个在报文上方的工具栏内,如图: 那个鲜艳的图标就是色彩规则的入口. 另一个是view-->coloring rules菜单. 点击进去即可看见所有的色彩规则的设置 ...

  10. Android 7.0新特性

    还望支持个人博客站:http://www.enjoytoday.cn 由于google目前不是无法直接在国内访问,故此,对于android 开发平台的7.0新特性做个保存.也可供大家查阅.原文转自an ...