并发编程 Future 与 CompletableFuture

 

package org.onepiece;

import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {

        println("Future-start");
        //创建ExecutorService,通过它向线程池提交任务
        ExecutorService executor = Executors.newCachedThreadPool();

        //向ExecutorService提交一个Callable对象
        Future<List<Integer>> future = executor.submit(new Callable<List<Integer>>() {
            //以异步的方式在新的线程中执行耗时的操作
            @Override
            public List<Integer> call() throws Exception {
                return getList();
            }
        });

        try {
            println("future-running");
            List<Integer> result = future.get(10, TimeUnit.SECONDS);
            println("future.get");
            println("Future结果: " + result.size());
        } catch (ExecutionException e) {
            //计算时抛出-异常
            println("Future计算异常:" + e.toString());
        } catch (InterruptedException e) {
            //当前线程在等待过程中被中断-异常
            println("Future线程中断异常:" + e.toString());
        } catch (TimeoutException e) {
            //在Future对象完成计算之前超时-异常
            println("Future超时异常:" + e.toString());
        }
        println("Future-end");


        println("");
        println("CompletableFuture-start");
        //创建CompletableFuture对象,它会包含计算的结果
        CompletableFuture<List<Integer>> compFuture = new CompletableFuture<>();

        //在另一个线程中以异步方式执行操作
        new Thread(() -> {
            try {
                println("CompletableFuture-running");

                List<Integer> list = getList();
                compFuture.complete(list);

                println("CompletableFuture.complete");
                //长时间计算的任务结束并得到结果时,返回Future返回值
            } catch (Exception ex) {
                //如果期间出现异常,
                //需要使用以下代码将导致CompletableFuture内发生问题的异常抛出
                compFuture.completeExceptionally(ex);
            }
        }).start();

        try {
            println("CompletableFuture.get");

            List<Integer> result2 = compFuture.get(10, TimeUnit.SECONDS);
            println("CompletableFuture结果: " + result2.size());
        } catch (ExecutionException e) {
            //计算时抛出-异常
            println("CompletableFuture计算异常:" + e.toString());
        } catch (InterruptedException e) {
            //当前线程在等待过程中被中断-异常
            println("CompletableFuture线程中断异常:" + e.toString());
        } catch (TimeoutException e) {
            //在Future对象完成计算之前超时-异常
            println("CompletableFuture超时异常:" + e.toString());
        }
        println("CompletableFuture-end");


        println("");
        println("---------main-end---------");
    }

    private static int Num = 1000000;

    /**
     * 耗时的方法
     */
    public static List<Integer> getList() {
        long time = System.currentTimeMillis();

        List<Integer> list = new LinkedList<>(); //new ArrayList<>();
        println("for-start");
        for (int i = 0; i < Num; i++) {
            list.add(i);
        }
        println("for-end: " + (System.currentTimeMillis() - time));

        println("map-start");
        List<Integer> mapList = list.stream().map(x -> x + 1).collect(Collectors.toList());
        println("map-end: " + (System.currentTimeMillis() - time));

        println("sorted-start");
        List<Integer> sortedList = mapList.stream().sorted((x, y) -> y - x).collect(Collectors.toList());
        println("sorted-end: " + (System.currentTimeMillis() - time));

        return sortedList;
    }

    private static void println(Object obj) {
        System.out.println(obj); //sout
    }
}

 

Future-start
future-running
for-start
for-end: 98
map-start
map-end: 234
sorted-start
sorted-end: 268
future.get
Future结果: 1000000
Future-end

CompletableFuture-start
CompletableFuture.get
CompletableFuture-running
for-start
for-end: 25
map-start
map-end: 649
sorted-start
sorted-end: 669
CompletableFuture结果: 1000000
CompletableFuture-end

---------main-end---------
CompletableFuture.complete
Future-start
future-running
for-start
for-end: 131
map-start
map-end: 258
sorted-start
sorted-end: 291
future.get
Future结果: 1000000
Future-end

CompletableFuture-start
CompletableFuture.get
CompletableFuture-running
for-start
for-end: 29
map-start
map-end: 672
sorted-start
sorted-end: 704
CompletableFuture.complete
CompletableFuture结果: 1000000
CompletableFuture-end

---------main-end---------

 

posted @ 2019-08-04 01:42  茗::流  阅读(204)  评论(0)    收藏  举报
如有雷同,纯属参考。如有侵犯你的版权,请联系我。