CompletableFuture 示例
package com.sykean.smartsite.pay.MyTest;import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;
/**
* @AuThor Administrator
* @ClassName TestCompletableFuture
* @description futrue测试
* @date 2020/6/16 0016 14:42
* @modifier Administrator
* @date 2020-06-16 14:42
* @version V1.0
*/
public class TestCompletableFuture {
public static void main(String[] args) throws Exception{
// test1();
test2();
// thenCombine();
}
/***
* 把两个任务的结果一块交给 thenCombine 来处理
*/
private static void thenCombine() throws ExecutionException, InterruptedException {
CompletableFuture<String> future1 = CompletableFuture.supplyAsync( () -> "then" );
CompletableFuture<String> future2 = CompletableFuture.supplyAsync( () -> "Combine" );
CompletableFuture<String> data = future1.thenCombine( future2, (s, s2) -> s + " " + s2 );
System.out.println("thenCombine执行结果:{}" + data.get());
}
private static void test2() throws ExecutionException, InterruptedException {
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
System.out.println("做第一件事");
waitSomeTime(1000);
return "做第一件事";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("做第二件事");
waitSomeTime(2000);
return "做第二件事";
});
CompletableFuture futureAll = CompletableFuture.allOf(future1,future2);
System.out.println("开始阻塞" + System.currentTimeMillis());
futureAll.join();
System.out.println("结束阻塞" + System.currentTimeMillis());
System.out.println(future1.isDone());
if (futureAll.isDone()){
System.out.println(future1.get());
System.out.println(future2.get());
System.out.println("总事件完成");
}
}
private static void waitSomeTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static Supplier<String> getStringSupplier() {
return String::new;
}
private static void test1() throws Exception{
Random rand = new Random();
CompletableFuture<Integer> future9 = CompletableFuture.supplyAsync(() -> {
waitSomeTime(1000 + rand.nextInt(1000));
return 100;
});
CompletableFuture<Integer> future10 = CompletableFuture.supplyAsync(() -> {
waitSomeTime(1000 + rand.nextInt(1000));
return 200;
});
//两个中任意一个计算完成,那么触发Runnable的执行
CompletableFuture<String> f = future10.applyToEither(future9, i -> i.toString());
//两个都计算完成,那么触发Runnable的执行
CompletableFuture f1 = future10.acceptEither(future9, (e) -> {
System.out.println(e);
});
System.out.println(f.get());
}
}
页:
[1]