JDK5新增了Future接口,用于描述一个异步计算的结果。使用Future获得异步执行结果时,要么调用阻塞方法get(),要么轮询看isDone()是否为true,这两种方法都不是很好,因为主线程也会被迫等待。
从Java 8开始引入了CompletableFuture,它针对Future做了改进,可以传入回调对象,当异步任务完成或者发生异常时,自动调用回调对象的回调方法。
当我们想要异步处理时,以前都是调用execute或subject方法,而CompletableFuture有自己的一些方法可以异步执行线程
CompletableFuture<Void> hello = CompletableFuture.runAsync(
() -> System.out.println("hello"));
CompletableFuture<String> result = CompletableFuture.supplyAsync(
() -> "sada");
System.out.println(result.join());
CompletableFuture.runAsync(()-> System.out.println("test1"+
Thread.currentThread().getName())).thenRun(()->System.out.println("test2"+
Thread.currentThread().getName()));
CompletableFuture.runAsync(()-> System.out.println("test1"+Thread.currentThread().getName())).thenRunAsync(()->
System.out.println("test2"+Thread.currentThread().getName()));
CompletableFuture.supplyAsync(() -> "hello world").thenAccept( s -> System.out.println( s + " test"));
CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> "aaa").thenApply(s -> "sa" + s);
System.out.println(stringCompletableFuture.join());
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "zhang");
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> " san");
CompletableFuture<String> my = future.thenCombine(future1, (f1, f2) -> f1 + f2);
System.out.println(my.join()); // zhang san
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "zhang");
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> " san");
future.thenAcceptBoth(future1, (f1, f2) -> System.out.println(f1+f2));
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "zhang");
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> " san");
future.acceptEither(future1,x -> System.out.println(x));
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> getUser());
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> " san");
CompletableFuture<String> resultFuture = future.applyToEither(future1, x -> x);
System.out.println(resultFuture.join());
@GetMapping("test")
public List<String> test(){
long start = System.currentTimeMillis();
List<String> s = new ArrayList<>();
s.add("a");
s.add("b");
s.add("c");
s.add("d");
List<CompletableFuture<String>> completableFutureList = s.stream().map(str -> CompletableFuture.supplyAsync(()
-> testService.getUsername(str))).collect(Collectors.toList());
List<String> userList = completableFutureList.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList());
System.out.println(System.currentTimeMillis()-start+"ms");
return userList;
}