CompletableFuture



import com.google.common.collect.Lists;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;


public class Test {
    public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
//        test();
//        System.out.println("___________________________________");
//        completableTest();
//        testGet();
        testJoin();
    }

    public static void testJoin(){
        CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(() -> {
            int i =1/0;
            return 1;
        });
        CompletableFuture.allOf(f1).join();
        System.out.println("CompletableFuture Test");

    }

    public static void testGet() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(() -> {
            int i =1/0;
            return 1;
        });
        f1.get();
        System.out.println("CompletableFuture Test");
    }

    private static void test() {
        Long t1 = System.currentTimeMillis();
        int sum = 0;
        for (int i = 0; i < 10; i++) {
            int t = 0;
            for (int j = 0; j < 2000000000; j++) {
                t++;
            }
            sum += t;
        }
        System.out.println(sum);
        System.out.println(System.currentTimeMillis() - t1);
    }

    private static void completableTest() throws InterruptedException, ExecutionException, TimeoutException {
        Long t1 = System.currentTimeMillis();
        ExecutorService executorService = Executors.newFixedThreadPool(20);

        List<CompletableFuture<Void>> futureList = Lists.newArrayList();
        AtomicInteger sum = new AtomicInteger();
        for (int i = 0; i < 10; i++) {
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                int t = 0;
                for (int j = 0; j < 2000000000; j++) {
                    t++;
                }
                sum.addAndGet(t);
            }, executorService);
            futureList.add(future);
        }
//        CompletableFuture<Void> combineFuture = CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0]));
//        combineFuture.join();
        CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0])).get(1000L, TimeUnit.SECONDS);
        System.out.println(sum);
        System.out.println(System.currentTimeMillis() - t1);
    }
}

 

上一篇:java8中CompletableFuture的使用介绍


下一篇:lambda表达式滥用之殇:解耦三层嵌套lambda表达式