JUC并发编程第二章之CompletableFuture[加强版的线程]

时间:2023-04-07 19:54:25

1、 创建线程的几种方式

new thread:

        //构造方法给指定的线程指定名称,推荐
        Thread thread = new Thread(t1) {
            @Override
            public void run() {
                //要执行的任务
            }
        };
        //启动线程
        thread.start();

new runnable:

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                //要执行的任务
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();

Future

        FutureTask<Integer> task = new FutureTask<>(() -> {
            System.out.println(执行的任务);
            return 100;
        });
        new Thread(task,t1).start();
        Integer integer = task.get();
        System.out.println(结果是+integer);

2、 Future的优缺点

优点: Future配合线程池能够显著提高程序的执行效率

public static void main(String[] args) throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        FutureTask<String> stringFutureTask1 = new FutureTask<>(() -> {
            TimeUnit.SECONDS.sleep(5);
            return over;
        });
        executorService.submit(stringFutureTask1);


        FutureTask<String> stringFutureTask2 = new FutureTask<>(() -> {
            TimeUnit.SECONDS.sleep(3);
            return over;
        });
        executorService.submit(stringFutureTask2);

        FutureTask<String> stringFutureTask3 = new FutureTask<>(() -> {
            TimeUnit.SECONDS.sleep(3);
            return over;
        });
        executorService.submit(stringFutureTask3);
        System.out.println(stringFutureTask1.get());
        System.out.println(stringFutureTask2.get());
        System.out.println(stringFutureTask3.get());
        executorService.shutdown();
        long endTime = System.currentTimeMillis();
        System.out.println(耗时了+(endTime-startTime));
    }

输出结果:
over
over
over
耗时了5084

可以看到如果是串行输出,结果是5s+3s+3s的耗时;


  • 缺点1:Get 方法容易导致堵塞

从上面的程序,我必须得到stringFutureTask1 执行完后,主线程才能执行任务, 输出耗时时间,我们的期望是 stringFutureTask1在耗时5s的时间内,主线程忙其他事情, 并询问下stringFutureTask1 是否执行完毕, 如果执行完毕,则输出耗时时间;

  • 缺点2:Get 方法没有最大等待时间

比如我们最多只能等待5s, 但是如果get()方法执行10s的话, 则会影响我们的程序

  • 缺点3: isDone 容易导致cpu轮训空转
   public static void main(String[] args) throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        FutureTask<String> stringFutureTask1 = new FutureTask<>(() -> {
            TimeUnit.SECONDS.sleep(5);
            return over;
        });
        executorService.submit(stringFutureTask1);
        executorService.shutdown();

        while (true) {
            if (stringFutureTask1.isDone()){
                long endTime = System.currentTimeMillis();
                System.out.println(耗时了 + (endTime - startTime));
            }
        }
    }

3、CompletableFuture对Future的改进

对于真正的异步处理我们希望可以通过传入回调函数,在Future结束时自动调用该函数;这样我们就不用等待结果了;

3.1、CompletableFuture的基本结构

public class CompletableFuture<T> implements Future<T>, CompletionStage<T>
  • CompletionStage 代表计算过程的一个阶段,一个阶段完成以后可能会触发另一个阶段;

  • 一个阶段的计算,可以是一个function,consumer或者runnable. 比如stage.thenApply(x->square(x)).thenAccept(x->system.out.print(x)).thenReturn(()->system.out.println())

  • 一个阶段的执行可能是被单个阶段的完成触发,也可能是由多个阶段一起触发;

3.2、创建CompletableFuture四种方式

  • runAsync 无返回值
返回值 具体方法
static CompletableFuture runAsync(Runnable runnable)
static CompletableFuture runAsync(Runnable runnable, Executor executor)

代码示例

public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },executorService);
        System.out.println(voidCompletableFuture.get());
    }
  • supplyAsync有返回值
返回值 具体方法
static CompletableFuture supplyAsync(Supplier supplier)
static CompletableFuture supplyAsync(Supplier supplier, Executor executor)
 public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return over;
        }, executorService);
        System.out.println(stringCompletableFuture.get());<br></br>        System.out.println(stringCompletableFuture.jion());
    }

输出结果
pool-1-thread-1
over
  • 指的注意的是,join方法和get方法,都可以获取返回值,而join没有处理异常而已;他不会要求抛出异常

3.3、CompletableFuture的流式调用

public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return over;
        }, executorService).whenComplete((v, e) -> {
            System.out.println(hello +v);
            if (e == null) {
                System.out.println(没有异常,更新完成);
            }
        }).exceptionally(s -> {
            s.printStackTrace();
            System.out.println(异常了,主线程先忙其他事情);
            return null;
        });
        System.out.println(主线程工作);
    }

扩展: 函数值编程接口JUC并发编程第二章之CompletableFuture[加强版的线程]

3.4、CompletableFuture常见的用法

对计算结果进行合并

public static void main(String[] args) throws Exception {
        CompletableFuture<Integer> task1 = CompletableFuture.supplyAsync(() -> {
            return 1;
        });
        CompletableFuture<Integer> task2 = CompletableFuture.supplyAsync(() -> {
            return 10;
        });

        CompletableFuture<Integer> integerCompletableFuture = task1.thenCombine(task2, (x, y) -> {
            return x + y;
        });
        System.out.println(integerCompletableFuture.get());
    }