【java】- CompletableFuture

CompletableFuture

创建异步线程任务

常量值作为CompletableFuture返回

//有时候是需要构建一个常量的CompletableFuture
public static <U> CompletableFuture<U> completedFuture(U value)

无返回值

//使用内置线程ForkJoinPool.commonPool(),根据runnable构建执行任务
public static CompletableFuture<Void> runAsync(Runnable runnable)

//指定自定义线程,根据runnable构建执行任务
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)

有返回值

//使用内置线程ForkJoinPool.commonPool(),根据supplier构建执行任务
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)

//指定自定义线程,根据supplier构建执行任务
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
ExecutorService executor = Executors.newSingleThreadExecutor();

CompletableFuture<Void> rFuture = CompletableFuture
        .runAsync(() -> System.out.println("hello siting"), executor);

//supplyAsync的使用
CompletableFuture<String> future = CompletableFuture
        .supplyAsync(() -> {
            System.out.print("hello ");
            return "siting";
        }, executor);

//阻塞等待,runAsync 的future 无返回值,输出null
System.out.println(rFuture.join());
String name = future.join();
System.out.println(name);
executor.shutdown(); 

--------输出结果--------
hello siting
null
hello siting

串行执行

img

thenRun - 任务完成则运行action,不关心上一个任务的结果,无返回值

public CompletableFuture<Void> thenRun(Runnable action)

public CompletableFuture<Void> thenRunAsync(Runnable action)
//action用指定线程池执行
public CompletableFuture<Void> thenRunAsync(Runnable action, Executor executor)
CompletableFuture<Void> future = CompletableFuture
        .runAsync(() -> "hello siting", executor)
        .thenRunAsync(() -> System.out.println("OK"), executor);
executor.shutdown();
--------输出结果--------
OK

thenAccept - 任务完成则运行action,依赖上一个任务的结果,无返回值

public CompletableFuture<Void> thenAccept(Consumer<? super T> action)

public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action)
//action用指定线程池执行
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action, Executor executor)
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<Void> future = CompletableFuture
        .supplyAsync(() -> "hello siting", executor)
        .thenAcceptAsync(System.out::println, executor);
executor.shutdown();
--------输出结果--------
hello siting

thenApply - 任务完成则运行fn,依赖上一个任务的结果,有返回值

public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)    
//fn用指定线程池执行
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<String> future = CompletableFuture
        .supplyAsync(() -> "hello world", executor)
        .thenApplyAsync(data -> {
            System.out.println(data); 
            return "OK";
        }, executor);
System.out.println(future.join());
executor.shutdown();
--------输出结果--------
hello world
OK

thenCompose - 任务完成则运行fn,依赖上一个任务的结果,有返回值

类似thenApply(区别是thenCompose的返回值是CompletionStagethenApply则是返回 U),提供该方法为了和其他CompletableFuture任务更好地配套组合使用

public <U> CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn) 

public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn)

public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn,Executor executor)        
ExecutorService executor = Executors.newSingleThreadExecutor();

//第一个异步任务,常量任务
CompletableFuture<String> f = CompletableFuture.completedFuture("OK");
//第二个异步任务
CompletableFuture<String> future = CompletableFuture
        .supplyAsync(() -> "hello world", executor)
        .thenComposeAsync(data -> {
            System.out.println(data);
            return f; //使用第一个任务作为返回
        }, executor);
System.out.println(future.join());
executor.shutdown();
--------输出结果--------
hello world
OK

并行执行

img

runAfterBoth - 并行执行完,然后执行action,不依赖上两个任务的结果,无返回值

public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other, Runnable action)
public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action)
public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action, Executor executor)
ExecutorService executor = Executors.newSingleThreadExecutor();

//第一个异步任务,常量任务
CompletableFuture<String> first = CompletableFuture.completedFuture("hello world");
CompletableFuture<Void> future = CompletableFuture
        //第二个异步任务
        .supplyAsync(() -> "hello siting", executor)
        // () -> System.out.println("OK") 是第三个任务
        .runAfterBothAsync(first, () -> System.out.println("OK"), executor);
executor.shutdown();
--------输出结果--------
OK

thenAcceptBoth - 并行执行完,然后执行action,依赖上两个任务的结果,无返回值

//调用方任务和other并行完成后执行action,action再依赖消费两个任务的结果,无返回值
public <U> CompletableFuture<Void> thenAcceptBoth(CompletionStage<? extends U> other,
        BiConsumer<? super T, ? super U> action)

//两个任务异步完成,fn再依赖消费两个任务的结果,无返回值,使用默认线程池
public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,
        BiConsumer<? super T, ? super U> action)  

//两个任务异步完成,fn(用指定线程池执行)再依赖消费两个任务的结果,无返回值                
public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,
        BiConsumer<? super T, ? super U> action, Executor executor) 
ExecutorService executor = Executors.newSingleThreadExecutor();

//第一个异步任务,常量任务
CompletableFuture<String> first = CompletableFuture.completedFuture("hello world");

CompletableFuture<Void> future = CompletableFuture
        //第二个异步任务
        .supplyAsync(() -> "hello siting", executor)
        // (w, s) -> System.out.println(s) 是第三个任务
        .thenAcceptBothAsync(first, (s, w) -> System.out.println(s), executor);
executor.shutdown();
--------输出结果--------
hello siting

thenCombine - 并行执行完,然后执行fn,依赖上两个任务的结果,有返回值

//调用方任务和other并行完成后,执行fn,fn再依赖消费两个任务的结果,有返回值
public <U,V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other, 
		BiFunction<? super T,? super U,? extends V> fn)

//两个任务异步完成,fn再依赖消费两个任务的结果,有返回值,使用默认线程池
public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,
        BiFunction<? super T,? super U,? extends V> fn)   

//两个任务异步完成,fn(用指定线程池执行)再依赖消费两个任务的结果,有返回值        
public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,
        BiFunction<? super T,? super U,? extends V> fn, Executor executor)  
ExecutorService executor = Executors.newSingleThreadExecutor();

//第一个异步任务,常量任务
CompletableFuture<String> first = CompletableFuture.completedFuture("hello world");
CompletableFuture<String> future = CompletableFuture
        //第二个异步任务
        .supplyAsync(() -> "hello siting", executor)
        // (w, s) -> System.out.println(s) 是第三个任务
        .thenCombineAsync(first, (s, w) -> {
            System.out.println(s);
            return "OK";
        }, executor);
System.out.println(future.join());
executor.shutdown();
--------输出结果--------
hello siting
OK

并行执行,谁先执行完则谁触发下一任务(二者选其最快)

img

runAfterEither - 上一个任务或者other任务完成, 运行action,不依赖前一任务的结果,无返回值

ublic CompletableFuture<Void> runAfterEither(CompletionStage<?> other, Runnable action)  

public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other, Runnable action)

//action用指定线程池执行
public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
		Runnable action, Executor executor)

ExecutorService executor = Executors.newSingleThreadExecutor();

//第一个异步任务,休眠1秒,保证最晚执行晚
CompletableFuture<String> first = CompletableFuture.supplyAsync(()->{
    try{ Thread.sleep(1000); }catch (Exception e){}
    System.out.println("hello world");
    return "hello world";
});

CompletableFuture<Void> future = CompletableFuture
        //第二个异步任务
        .supplyAsync(() ->{
            System.out.println("hello siting");
            return "hello siting";
        } , executor)
        //() ->  System.out.println("OK") 是第三个任务
        .runAfterEitherAsync(first, () ->  System.out.println("OK") , executor);
executor.shutdown();
--------输出结果--------
hello siting
OK

acceptEither - 上一个任务或者other任务完成, 运行action,依赖最先完成任务的结果,无返回值

public CompletableFuture<Void> acceptEither(CompletionStage<? extends T> other,
		Consumer<? super T> action)

public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other,
		Consumer<? super T> action, Executor executor)       

//action用指定线程池执行
public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other,
		Consumer<? super T> action, Executor executor)     
ExecutorService executor = Executors.newSingleThreadExecutor();

//第一个异步任务,休眠1秒,保证最晚执行晚
CompletableFuture<String> first = CompletableFuture.supplyAsync(()->{
    try{ Thread.sleep(1000);  }catch (Exception e){}
    return "hello world";
});

CompletableFuture<Void> future = CompletableFuture
        //第二个异步任务
        .supplyAsync(() -> "hello siting", executor)
        // data ->  System.out.println(data) 是第三个任务
        .acceptEitherAsync(first, data ->  System.out.println(data) , executor);
executor.shutdown();

--------输出结果--------
hello siting     

applyToEither - 上一个任务或者other任务完成, 运行fn,依赖最先完成任务的结果,有返回值

public <U> CompletableFuture<U> applyToEither(CompletionStage<? extends T> other,
		Function<? super T, U> fn) 

public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other,
		Function<? super T, U> fn)         

//fn用指定线程池执行
public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other,
		Function<? super T, U> fn, Executor executor)   
ExecutorService executor = Executors.newSingleThreadExecutor();

//第一个异步任务,休眠1秒,保证最晚执行晚
CompletableFuture<String> first = CompletableFuture.supplyAsync(()->{
    try{ Thread.sleep(1000);  }catch (Exception e){}
    return "hello world";
});

CompletableFuture<String> future = CompletableFuture
        //第二个异步任务
        .supplyAsync(() -> "hello siting", executor)
        // data ->  System.out.println(data) 是第三个任务
        .applyToEitherAsync(first, data ->  {
            System.out.println(data);
            return "OK";
        } , executor);
System.out.println(future);
executor.shutdown();
--------输出结果--------
hello siting
OK

处理任务结果或者异常

exceptionally-处理异常

img

exceptionally

如果之前的处理环节有异常问题,则会触发exceptionally的调用相当于 try...catch

public CompletableFuture<T> exceptionally(Function<Throwable, ? extends T> fn)
CompletableFuture<Integer> first = CompletableFuture
        .supplyAsync(() -> {
            if (true) {
                throw new RuntimeException("main error!");
            }
            return "hello world";
        })
        .thenApply(data -> 1)
        .exceptionally(e -> {
            e.printStackTrace(); // 异常捕捉处理,前面两个处理环节的日常都能捕获
            return 0;
        });

handle-任务完成或者异常时运行fn,返回值为fn的返回

相比exceptionally而言,即可处理上一环节的异常也可以处理其正常返回值

public <U> CompletableFuture<U> handle(BiFunction<? super T, Throwable, ? extends U> fn) 

public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn) 

public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn, 
		Executor executor)  
CompletableFuture<Integer> first = CompletableFuture
        .supplyAsync(() -> {
            if (true) { throw new RuntimeException("main error!"); }
            return "hello world";
        })
        .thenApply(data -> 1)
        .handleAsync((data,e) -> {
            e.printStackTrace(); // 异常捕捉处理
            return data;
        });
System.out.println(first.join());
--------输出结果--------
java.util.concurrent.CompletionException: java.lang.RuntimeException: main error!
	... 5 more

whenComplete-任务完成或者异常时运行action,有返回值

  • whenCompletehandle的区别在于,它不参与返回结果的处理,把它当成监听器即可
  • 即使异常被处理,在CompletableFuture外层,异常也会再次复现
  • 使用whenCompleteAsync时,返回结果则需要考虑多线程操作问题,毕竟会出现两个线程同时操作一个结果
public CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throwable> action) 

public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action) 

public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action,
		Executor executor)  
CompletableFuture<AtomicBoolean> first = CompletableFuture
        .supplyAsync(() -> {
            if (true) {  throw new RuntimeException("main error!"); }
            return "hello world";
        })
        .thenApply(data -> new AtomicBoolean(false))
        .whenCompleteAsync((data,e) -> {
            //异常捕捉处理, 但是异常还是会在外层复现
            System.out.println(e.getMessage());
        });
first.join();
--------输出结果--------
java.lang.RuntimeException: main error!
Exception in thread "main" java.util.concurrent.CompletionException: java.lang.RuntimeException: main error!
	... 5 more

多个任务的简单组合

public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)

img

img

 CompletableFuture<Void> future = CompletableFuture
        .allOf(CompletableFuture.completedFuture("A"),
                CompletableFuture.completedFuture("B"));
//全部任务都需要执行完
future.join();
CompletableFuture<Object> future2 = CompletableFuture
        .anyOf(CompletableFuture.completedFuture("C"),
                CompletableFuture.completedFuture("D"));
//其中一个任务行完即可
future2.join();

cancel - 取消执行线程任务

// mayInterruptIfRunning 无影响;如果任务未完成,则返回异常
public boolean cancel(boolean mayInterruptIfRunning) 

//任务是否取消
public boolean isCancelled()
CompletableFuture<Integer> future = CompletableFuture
        .supplyAsync(() -> {
            try { Thread.sleep(1000);  } catch (Exception e) { }
            return "hello world";
        })
        .thenApply(data -> 1);

System.out.println("任务取消前:" + future.isCancelled());
// 如果任务未完成,则返回异常,需要对使用exceptionally,handle 对结果处理
future.cancel(true);
System.out.println("任务取消后:" + future.isCancelled());
future = future.exceptionally(e -> {
    e.printStackTrace();
    return 0;
});
System.out.println(future.join());
--------输出结果--------
任务取消前:false
任务取消后:true
java.util.concurrent.CancellationException
	at java.util.concurrent.CompletableFuture.cancel(CompletableFuture.java:2276)
	at Test.main(Test.java:25)

任务的获取和完成与否判断

// 任务是否执行完成
public boolean isDone()

//阻塞等待 获取返回值
public T join()

// 阻塞等待 获取返回值,区别是get需要返回受检异常
public T get()

//等待阻塞一段时间,并获取返回值
public T get(long timeout, TimeUnit unit)

//未完成则返回指定value
public T getNow(T valueIfAbsent)

//未完成,使用value作为任务执行的结果,任务结束。需要future.get获取
public boolean complete(T value)

//未完成,则是异常调用,返回异常结果,任务结束
public boolean completeExceptionally(Throwable ex)

//判断任务是否因发生异常结束的
public boolean isCompletedExceptionally()

//强制地将返回值设置为value,无论该之前任务是否完成;类似complete
public void obtrudeValue(T value)

//强制地让异常抛出,异常返回,无论该之前任务是否完成;类似completeExceptionally
public void obtrudeException(Throwable ex) 
CompletableFuture<Integer> future = CompletableFuture
        .supplyAsync(() -> {
            try { Thread.sleep(1000);  } catch (Exception e) { }
            return "hello world";
        })
        .thenApply(data -> 1);

System.out.println("任务完成前:" + future.isDone());
future.complete(10);
System.out.println("任务完成后:" + future.join());
--------输出结果--------
任务完成前:false
任务完成后:10

例子

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.function.*;

public class CompletableFutureTest01 {


    private static final Logger log = LoggerFactory.getLogger(CompletableFutureTest01.class);

    public static void main(String[] args) throws Exception {

        // whenCompleteTest();
        // thenApply接收一个函数作为参数,使用该函数处理上一个CompletableFuture调用的结果,并返回一个具有处理结果的Future对象。
        // thenApplyTest();
        // thenComposeTest();
        // thenAccepteTest();
        // thenAcceptBothTest();
        // thenRunTest();
        // thenCombineTest();
        // applyToEitherTest();
        // acceptEitherTest();
        // runAfterEitherTest();
        // anyOfTest();
        // allOfTest();
        // boilWaterTest0();
        // boilWaterTest1();
    }

    private static void whenCompleteTest() throws Exception  {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(
                () -> {
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {

                    }
                    if (new Random().nextInt(10) % 2 == 0) {
                        int i = 12 / 0;
                    }
                    System.out.println("执行结束!");
                    return "test";
                })
                // 任务完成或异常方法完成时执行该方法 如果出现了异常,任务结果为null
                .whenComplete((t, e) -> System.out.println(t+" 执行完成!"+ e.getMessage()))
                // 出现异常时先执行该方法
                .exceptionally(t -> {
                    System.out.println("执行失败:" + t.getMessage());
                    return "异常xxxx";
                });
        future.get();
        System.err.println("============");
    }

    /** thenApply接收一个函数作为参数,使用该函数处理上一个CompletableFuture调用的结果,并返回一个具有处理结果的Future对象。
     * public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
     * public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)
     */
    private static void thenApplyTest() throws Exception  {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            int result = 100;
            System.out.println("第一次运算:" + result);
            return result;
        }).thenApply(number -> {
            int result = number * 3;
            System.out.println("第二次运算:" + result);
            return result;
        });
        future.get();
        System.err.println("============");
    }

    /** thenCompose的参数为一个返回CompletableFuture实例的函数,该函数的参数是先前计算步骤的结果。
     * thenApply转换的是泛型中的类型,返回的是同一个CompletableFuture;
     * thenCompose将内部的CompletableFuture调用展开来并使用上一个CompletableFutre调用的结果在下一步的CompletableFuture调用中进行运算,是生成一个新的CompletableFuture。
     * public <U> CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn);
     * public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn) ;
     */
    private static void thenComposeTest() throws Exception  {
        CompletableFuture<Integer> future = CompletableFuture
                .supplyAsync(() -> {
                    int number = new Random().nextInt(30);
                    System.out.println("第一次运算:" + number);
                    return number;
                })
                .thenCompose(param -> CompletableFuture.supplyAsync(() -> {
                    int number = param * 2;
                    System.out.println("第二次运算:" + number);
                    return number;
                }));
        future.get();
        System.err.println("============");
    }

    /** thenAccept():对单个结果进行消费
     * 观察该系列函数的参数类型可知,它们是函数式接口Consumer,这个接口只有输入,没有返回值。
     * public CompletionStage<Void> thenAccept(Consumer<? super T> action);
     * public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);
     * @throws Exception
     */
    private static void thenAccepteTest() throws Exception  {
        CompletableFuture<Void> future = CompletableFuture
                .supplyAsync(() -> {
                    int number = new Random().nextInt(10);
                    System.out.println("第一次运算:" + number);
                    return number;
                }).thenAccept(number ->
                        System.out.println("第二次运算:" + number * 5));

        future.get();
        System.err.println("============");
    }

    /**
     * thenAcceptBoth函数的作用是,当两个CompletionStage都正常完成计算的时候,就会执行提供的action消费两个异步的结果。
     * public <U> CompletionStage<Void> thenAcceptBoth(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);
     * public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);
     * @throws Exception
     */
    private static void thenAcceptBothTest() throws Exception  {
        CompletableFuture<Integer> futrue1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int number = new Random().nextInt(3) + 1;
                try {
                    TimeUnit.SECONDS.sleep(number);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("任务1结果:" + number);
                return number;
            }
        });

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int number = new Random().nextInt(3) + 1;
                try {
                    TimeUnit.SECONDS.sleep(number);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("任务2结果:" + number);
                return number;
            }
        });

        futrue1.thenAcceptBoth(future2, new BiConsumer<Integer, Integer>() {
            @Override
            public void accept(Integer x, Integer y) {
                System.out.println("最终结果:" + (x + y));
            }
        });
        futrue1.get();
        System.err.println("============");
    }

    /** thenRun也是对线程任务结果的一种消费函数,与thenAccept不同的是,
     * thenRun会在上一阶段 CompletableFuture计算完成的时候执行一个Runnable,
     * 而Runnable并不使用该CompletableFuture计算的结果。
     * public CompletionStage<Void> thenRun(Runnable action);
     * public CompletionStage<Void> thenRunAsync(Runnable action);
     */
    private static void thenRunTest() throws Exception  {
        CompletableFuture<Void> futrue1 = CompletableFuture.supplyAsync(() -> {
            int number = new Random().nextInt(10);
            System.out.println("第一阶段:" + number);
            return number;
        }).thenRun(() ->
                System.out.println("thenRun 执行"));
        futrue1.get();
        System.err.println("============");
    }


    /** thenCombine 合并两个线程任务的结果,并进一步处理。
     * public <U,V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);
     * public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);
     * public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn, Executor executor);
     * @throws Exception
     */
    private static void thenCombineTest() throws Exception  {
        CompletableFuture<Integer> future1 = CompletableFuture
                .supplyAsync(new Supplier<Integer>() {
                    @Override
                    public Integer get() {
                        int number = new Random().nextInt(10);
                        System.out.println("任务1结果:" + number);
                        return number;
                    }
                });
        CompletableFuture<Integer> future2 = CompletableFuture
                .supplyAsync(new Supplier<Integer>() {
                    @Override
                    public Integer get() {
                        int number = new Random().nextInt(10);
                        System.out.println("任务2结果:" + number);
                        return number;
                    }
                });
        CompletableFuture<Integer> result = future1
                .thenCombine(future2, new BiFunction<Integer, Integer, Integer>() {
                    @Override
                    public Integer apply(Integer x, Integer y) {
                        return x + y;
                    }
                });
        result.get();
        System.out.println("组合后结果:" + result.get());
        System.err.println("============");
    }

    /**
     * applyToEither
     * 两个线程任务相比较,先获得执行结果的,就对该结果进行下一步的转化操作。
     * public <U> CompletionStage<U> applyToEither(CompletionStage<? extends T> other,Function<? super T, U> fn);
     * public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn);
     * @throws Exception
     */
    private static void applyToEitherTest() throws Exception  {
        CompletableFuture<Integer> future1 = CompletableFuture
                .supplyAsync(new Supplier<Integer>() {
                    @Override
                    public Integer get() {
                        int number = new Random().nextInt(10);
                        try {
                            TimeUnit.SECONDS.sleep(number);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("任务1结果:" + number);
                        return number;
                    }
                });
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int number = new Random().nextInt(10);
                try {
                    TimeUnit.SECONDS.sleep(number);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("任务2结果:" + number);
                return number;
            }
        });

        future1.applyToEither(future2, new Function<Integer, Integer>() {
            @Override
            public Integer apply(Integer number) {
                System.out.println("最快结果:" + number);
                return number * 2;
            }
        });
        future1.get();
        System.err.println("============");
    }

    /**
     * acceptEither
     * 两个线程任务相比较,先获得执行结果的,就对该结果进行下一步的消费操作。
     * public CompletionStage<Void> acceptEither(CompletionStage<? extends T> other,Consumer<? super T> action);
     * public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,Consumer<? super T> action);
     * @throws Exception
     */
    private static void acceptEitherTest() throws Exception  {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int number = new Random().nextInt(10) + 1;
                try {
                    TimeUnit.SECONDS.sleep(number);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("第一阶段:" + number);
                return number;
            }
        });

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int number = new Random().nextInt(10) + 1;
                try {
                    TimeUnit.SECONDS.sleep(number);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("第二阶段:" + number);
                return number;
            }
        });

        future1.acceptEither(future2, new Consumer<Integer>() {
            @Override
            public void accept(Integer number) {
                System.out.println("最快结果:" + number);
            }
        });
        future1.get();
        System.err.println("============");
    }

    /** runAfterEither
     * 两个线程任务相比较,有任何一个执行完成,就进行下一步操作,不关心运行结果。
     * public CompletionStage<Void> runAfterEither(CompletionStage<?> other,Runnable action);
     * public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action);
     * @throws Exception
     */
    private static void runAfterEitherTest() throws Exception  {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int number = new Random().nextInt(5);
                try {
                    TimeUnit.SECONDS.sleep(number);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("任务1结果:" + number);
                return number;
            }
        });

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int number = new Random().nextInt(5);
                try {
                    TimeUnit.SECONDS.sleep(number);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("任务2结果:" + number);
                return number;
            }
        });

        future1.runAfterEither(future2, new Runnable() {
            @Override
            public void run() {
                System.out.println("已经有一个任务完成了");
            }
        }).join();
        System.err.println("============");
    }

    /**
     * anyOf() 的参数是多个给定的 CompletableFuture,当其中的任何一个完成时,方法返回这个 CompletableFuture。
     * public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)
     * @throws Exception
     */
    private static void anyOfTest() throws Exception  {
        Random random = new Random();
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(random.nextInt(1));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello";
        });

        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(random.nextInt(1));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "world";
        });
        CompletableFuture<Object> result = CompletableFuture.anyOf(future1, future2);
        Object o = result.get();
        System.out.println(o);
        System.err.println("============");
    }

    /**
     * allOf方法用来实现多 CompletableFuture 的同时返回。
     * public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
     * @throws Exception
     */
    private static void allOfTest() throws Exception  {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("future1完成!");
            return "future1完成!";
        });

        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("future2完成!");
            return "future2完成!";
        });

        CompletableFuture<Void> combindFuture = CompletableFuture.allOf(future1, future2);

        try {
            combindFuture.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 对于烧水泡茶这个程序,
     * 一种最优的分工方案:
     * 用两个线程 T1 和 T2 来完成烧水泡茶程序,
     * T1 负责洗水壶、烧开水、泡茶这三道工序,
     * T2 负责洗茶壶、洗茶杯、拿茶叶三道工序,
     * 其中 T1 在执行泡茶这道工序时需要等待 T2 完成拿茶叶的工序。
     */
    private static void boilWaterTest0() throws Exception  {
        // 创建任务T2的FutureTask
        FutureTask<String> ft2 = new FutureTask<>(new T2Task());
        // 创建任务T1的FutureTask
        FutureTask<String> ft1 = new FutureTask<>(new T1Task(ft2));
        // 线程T1执行任务ft2
        Thread T1 = new Thread(ft2);
        T1.start();
        // 线程T2执行任务ft1
        Thread T2 = new Thread(ft1);
        T2.start();
        // 等待线程T1执行结果
        System.out.println(ft1.get());

    }

    private static void boilWaterTest1() throws Exception  {
        //任务1:洗水壶->烧开水
        CompletableFuture<Void> f1 = CompletableFuture
                .runAsync(() -> {
                    System.out.println("T1:洗水壶...");
                    sleep(1, TimeUnit.SECONDS);

                    System.out.println("T1:烧开水...");
                    sleep(15, TimeUnit.SECONDS);
                });
        //任务2:洗茶壶->洗茶杯->拿茶叶
        CompletableFuture<String> f2 = CompletableFuture
                .supplyAsync(() -> {
                    System.out.println("T2:洗茶壶...");
                    sleep(1, TimeUnit.SECONDS);

                    System.out.println("T2:洗茶杯...");
                    sleep(2, TimeUnit.SECONDS);

                    System.out.println("T2:拿茶叶...");
                    sleep(1, TimeUnit.SECONDS);
                    return "龙井";
                });
        //任务3:任务1和任务2完成后执行:泡茶
        CompletableFuture<String> f3 = f1.thenCombine(f2, (__, tf) -> {
            System.out.println("T1:拿到茶叶:" + tf);
            System.out.println("T1:泡茶...");
            return "上茶:" + tf;
        });
        //等待任务3执行结果
        System.out.println(f3.join());
    }

    static void sleep(int t, TimeUnit u){
        try {
            u.sleep(t);
        } catch (InterruptedException e) {
        }
    }

    // T1Task需要执行的任务:
    // 洗水壶、烧开水、泡茶
    static class T1Task implements Callable<String> {
        FutureTask<String> ft2;
        // T1任务需要T2任务的FutureTask
        T1Task(FutureTask<String> ft2){
            this.ft2 = ft2;
        }
        @Override
        public String call() throws Exception {
            System.out.println("T1:洗水壶...");
            TimeUnit.SECONDS.sleep(1);

            System.out.println("T1:烧开水...");
            TimeUnit.SECONDS.sleep(15);
            // 获取T2线程的茶叶
            String tf = ft2.get();
            System.out.println("T1:拿到茶叶:"+tf);

            System.out.println("T1:泡茶...");
            return "上茶:" + tf;
        }
    }
    // T2Task需要执行的任务:
    // 洗茶壶、洗茶杯、拿茶叶
    static class T2Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("T2:洗茶壶...");
            TimeUnit.SECONDS.sleep(1);

            System.out.println("T2:洗茶杯...");
            TimeUnit.SECONDS.sleep(2);

            System.out.println("T2:拿茶叶...");
            TimeUnit.SECONDS.sleep(1);
            return "龙井";
        }
    }
}
posted @   明小子@  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示