package com.test.example;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CompletFutureExample {
public static void main(String[] args) throws Exception{
exceptionHandle();
}
public static void futureExample() throws ExecutionException, InterruptedException {
/*
* 虽然Future以及相关使用方法提供了异步执行任务的能力,
* 但是对于结果的获取却是很不方便,
* 只能通过阻塞或者轮询的方式得到任务的结果。
* ,轮询的方式又会耗费无谓的CPU资源,
* 而且也不能及时地得到计算结果
* */
/*
* Future 接口的局限性
*
* 了解了Future的使用,这里就要谈谈Future的局限性。
* Future很难直接表述多个Future 结果之间的依赖性,
* 开发中,我们经常需要达成以下目的:
(1)将两个异步计算合并为一个(这两个异步计算之间相互独立,
* 同时第二个又依赖于第一个的结果)
(2)等待 Future 集合中的所有任务都完成。
(3)仅等待 Future 集合中最快结束的任务完成,并返回它的结果。
* */
ExecutorService executorService = Executors.newFixedThreadPool(10);
Future<Integer> f = executorService.submit(() -> {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum = sum + i;
Thread.sleep(5);
}
return sum;
});
while (!f.isDone()) {//f.isDone();方法是阻塞式的
System.out.println("计算任务还未执行完");
}
executorService.shutdown();
System.out.println(f.get());
}
public static void completableFutureExample() {
/*
主动完成计算
*Async结尾的方法都是可以异步执行的,如果指定了线程池,会在指定的线程池中执行,
* 如果没有指定,默认会在ForkJoinPool.commonPool()中执行。
*
* */
/*变换结果*/
String result = CompletableFuture.supplyAsync(() -> {
return "hello";
}).thenApplyAsync(item -> {
item = item + " world";
return item;
}).join();
System.out.println("result:"+result);
}
public static void Consumer(){
/*消费结果*/
/*这些方法只是针对结果进行消费,入参是Consumer,没有返回值*/
CompletableFuture.supplyAsync(() -> {
return "hello";
}).thenAccept(v -> {
System.out.println("comsumer:" + v);
});
}
public static void combine(){
/*
*结合两个CompletionStage的结果,进行转化后返回
* */
String reault=CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (Exception e) {
}
return "hello";
}).thenCombine(CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "world";
}), (s1, s2) -> {
return s1 + " " + s2;
}
).join();
System.out.println("result:"+reault);
}
public static void compare() {
/*
* 两种渠道完成同一个事情,就可以调用这个方法,找一个最快的结果进行处理,最终有返回值。
* */
String result=CompletableFuture.supplyAsync(()->{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "1";
}).applyToEither(CompletableFuture.supplyAsync(()->{
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "2";
}),(s)->{
return s;
}).join();
System.out.println("result:"+result);
}
public static void exceptionHandle(){
String result=CompletableFuture.supplyAsync(()->{
int i=10/0;
return "hello";
}).exceptionally(e->{
return "出现异常,默认结果";
}).join();
System.out.println("result:"+result);
}
}