CompletableFuture - 常用API(上)

原创转载请注明出处:http://agilestyle.iteye.com/blog/2427512

 

先看一个简单的例子

package org.fool.java8.completable;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

public class CompletableFutureTest4 {

    private final static Random RANDOM = new Random(System.currentTimeMillis());

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(2);

//        CompletableFuture.supplyAsync(CompletableFutureTest4::get, executorService)
//                .thenApply(CompletableFutureTest4::multiply)
//                .whenComplete((v, t) -> {
//            Optional.ofNullable(v).ifPresent(System.out::println);
//            Optional.ofNullable(t).ifPresent(Throwable::printStackTrace);
//        });

        System.out.println("===========main start no block============");

        List<Integer> productionIds = Arrays.asList(1, 2, 3, 4, 5);
//        Stream<CompletableFuture<Double>> completableFutureStream =
//                productionIds.stream().map(i -> CompletableFuture.supplyAsync(() -> queryProduction(i), executorService));
//
//        Stream<CompletableFuture<Double>> multiplyFutures = completableFutureStream.map(future -> future.thenApply(CompletableFutureTest4::multiply));
//
//        List<Double> result = multiplyFutures.map(CompletableFuture::join).collect(toList());

        List<Double> result = productionIds.stream()
                .map(i -> CompletableFuture.supplyAsync(() -> queryProduction(i), executorService))
                .map(future -> future.thenApply(CompletableFutureTest4::multiply))
                .map(future -> future.thenApply(CompletableFutureTest4::subtract))
                .map(CompletableFuture::join).collect(toList());

        System.out.println(result);

        System.out.println("=========main end no block==========");
    }

    private static double get() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        double result = RANDOM.nextDouble();
        System.out.println(Thread.currentThread().getName() + ":" + result);
        return result;
    }

    private static double queryProduction(int i) {
        return CompletableFutureTest4.get();
    }

    private static double multiply(double value) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return value * 10d;
    }

    private static double subtract(double value) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return value - 1;
    }
}

Note:  将列表中的数字,统一放到一个线程池中处理,  先get,接着multiply,然后substract,最后join


Console  Output


 

thenApply

private static void testThenApply() {
	CompletableFuture.supplyAsync(() -> 1)
			.thenApply(i -> Integer.sum(i, 10))
			.whenComplete((v, t) -> System.out.println(v));
}

 Console  Output



handle

private static void testHandle() {
	CompletableFuture.supplyAsync(() -> 1)
			.handle((v, t)-> Integer.sum(v, 10))
			.whenComplete((v, t) -> System.out.println(v));
}

 Console Output


 

thenRun

private static void testThenRun() {
	CompletableFuture.supplyAsync(() -> 1)
			.handle((v, t)-> Integer.sum(v, 10))
			.whenComplete((v, t) -> System.out.println(v))
			.thenRun(() -> System.out.println("action ended..."));
}

Console Output


 

thenAccept

private static void testThenAccept() {
	CompletableFuture.supplyAsync(() -> 1)
			.thenApply(i -> Integer.sum(i, 10))
			.thenAccept(System.out::println);
}

Console Output


 

thenCompose

private static void testThenCompose() {
	CompletableFuture.supplyAsync(() -> 1)
			.thenCompose(i -> CompletableFuture.supplyAsync(() -> 10 * i))
			.thenAccept(System.out::println);
}

Console Output


 

thenCombine

private static void testThenCombine() {
	CompletableFuture.supplyAsync(() -> 1)
			.thenCombine(CompletableFuture.supplyAsync(() -> 2), (r1, r2) -> r1 + r2)
			.thenAccept(System.out::println);
}

Console Output


 

thenAcceptBoth

private static void testThenAcceptBoth() {
	CompletableFuture.supplyAsync(() -> 1)
			.thenAcceptBoth(CompletableFuture.supplyAsync(() -> 2), (r1, r2) -> {
				System.out.println(r1);
				System.out.println(r2);
				System.out.println(r1 + r2);
			});
}

Console Output


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值