异步任务CompletableFuture

        CompletableFuture能够联想到的是Future,其次呢,其还实现了CompletionStage,这个作用呢就是对一些执行时间比较长的任务进行拆分。

        在使用的时候呢需要提供一个线程池(线程工厂跟拒绝策略是默认的,为方便,为未指定,有需求可自行添加)

@Configuration
public class ExecutorConfig {
     @Bean
     public ThreadPoolExecutor ThreadPool(){

          ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5,
                  10,
                  100,
                  TimeUnit.SECONDS,
                  new LinkedBlockingQueue<>(10));
          return threadPool;
     }
}

然后调用CompletableFuture.supplyAsync()跟allof().join()方法去完成任务的执行

@Autowired
    private ThreadPoolExecutor ThreadPool;
    @Override
    public List<String> Test() {
        ArrayList<String> list = new ArrayList<>();
        //分片去执行各个需求的任务
        try {
            CompletableFuture<Integer> A1 = CompletableFuture.supplyAsync(() -> {
                System.out.println( "当前执行任务的是" + Thread.currentThread().getName());
                return 100 - 1;
            }, ThreadPool);
            CompletableFuture<Integer> A2 = CompletableFuture.supplyAsync(() -> {
                System.out.println( "当前执行任务的是:" + Thread.currentThread().getName());
                return 100 * 1 - 1000 + 2990 - 8930 * 99442;
            }, ThreadPool);
            Thread.sleep(3);
            CompletableFuture<Integer> A3 = CompletableFuture.supplyAsync(() -> {
                System.out.println( "当前执行任务的是:" + Thread.currentThread().getName());
                return 100 * 1 - 1000 + 2990 - 8930 * 99442 / 8821 * 45;
            }, ThreadPool);
            CompletableFuture<Integer> A4 = CompletableFuture.supplyAsync(() -> {
                System.out.println( "当前执行任务的是:" + Thread.currentThread().getName());
                return 100 * 1 - 1000 + 2990 - 8930 * 99442 / 8821 * 45 - 100 + 99 * (88 + 1);
            }, ThreadPool);
            CompletableFuture<Integer> A5 = CompletableFuture.supplyAsync(() -> {
                System.out.println( "当前执行任务的是:" + Thread.currentThread().getName());
                return 100 * 1 - 1000 + 2990 - 8930 * 99442 / 8821 * 45 - 100 + 99 * (88 + 1) / 100;
            }, ThreadPool);
            //等待所有异步任务执行完场
            CompletableFuture.allOf(A1,A2,A3,A4,A5).join();
            //封装返回结果
            list.add(String.valueOf(A1.get()));
            list.add(String.valueOf(A2.get()));
            list.add(String.valueOf(A3.get()));
            list.add(String.valueOf(A4.get()));
            list.add(String.valueOf(A5.get()));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值