CompletableFuture 使用详解
话不多说,直接上代码:
public static void test5() throws Exception {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("run end.......");
});
// future.get();
}
public static void test6() throws Exception {
List<CompletableFuture> list = new ArrayList(10);
for (int i = 0; i < 10; i++) {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// System.out.println(">>>>>>>>>>>");
return "ad";
});
list.add(future);
}
int js = 0;
for (CompletableFuture completableFuture : list) {
completableFuture.get();
// System.out.println("是否获取到了"+completableFuture.isDone());
if (completableFuture.isDone()) {
System.out.println(++js);
// System.out.println("是否获取到了"+completableFuture.isDone());
System.out.println("返回的结果" + completableFuture.get());
} else {
System.out.println("未获取到------------------------------->");
}
}
System.out.println("----------------------->>>>>>>>end");
}
/**
* 当CompletableFuture的计算结果完成,或者抛出异常的时候,可以执行特定的Action。主要是下面的方法:
*
* 可以看到Action的类型是BiConsumer<? super T,? super Throwable>它可以处理正常的计算结果,或者异常情况。
* whenComplete 和 whenCompleteAsync 的区别:
* whenComplete:是执行当前任务的线程执行继续执行 whenComplete 的任务。
* whenCompleteAsync:是执行把 whenCompleteAsync 这个任务继续提交给线程池来进行执行。
*
* @throws Exception
*/
public static void test7() throws Exception {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (true) {
int c = 12 / 0; //抛异常
}
System.out.println("run end.......");
});
// BiConsumer<? super T, ? super Throwable> biConsumer = ;
future.whenComplete(new BiConsumer<Void, Throwable>() {
@Override
public void accept(Void aVoid, Throwable cc) {
System.out.println("完成任务");
}
});
future.get();
}
public static void test8() throws Exception {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (3 > 2) {
int c = 12 / 0; //抛异常
}
System.out.println("run end.......");
return "第一个结束";
});
// BiConsumer<? super T, ? super Throwable> biConsumer = ;
future.whenComplete(new BiConsumer<String, Throwable>() {
@Override
public void accept(String s, Throwable throwable) {
System.out.println(s);
System.out.println("完成任务");
System.out.println(throwable);
if (null != throwable) {
System.out.println("捕获异常");
}
}
});
//只阻塞future.whenComplete 不阻塞,future.whenCompleteAsync
String res = future.get();
System.out.println(res);
}
public static void test9() throws Exception {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (3 > 2) {
int c = 12 / 0; //抛异常
}
System.out.println("run end.......");
return "第一个结束";
});
// future.whenComplete(new BiConsumer<String, Throwable>() {
// @Override
// public void accept(String s, Throwable throwable) {
// System.out.println("处理结束任务");
// System.out.println(s);
// System.out.println("完成任务");
// System.out.println(throwable);
// if(null!=throwable){
// System.out.println("捕获异常");
// }
// }
// });
future.exceptionally(new Function<Throwable, String>() {
@Override
public String apply(Throwable throwable) {
System.out.println("exceptionally 执行报异常~~");
return "exceptionally异常返回";
}
});
}
public static void test_10() throws Exception {
CompletableFuture<Long> futures = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (1 > 2) {
int c = 12 / 0; //抛异常
}
System.out.println("run end.......");
return 1L;
}).thenApply(new Function<Long, Long>() {
@Override
public Long apply(Long aLong) {
System.out.println("当前任务的事务~~~~");
long res = aLong * 5;
System.out.println("当前的结果~~~" + res);
return res;
}
});
/**
* 只阻塞future.whenComplete 不阻塞,future.whenCompleteAsync
*/
long result = futures.get();
System.out.println(result);
}
/**
* 3、 thenApply 方法
* 当一个线程依赖另一个线程时,可以使用 thenApply 方法来把这两个线程串行化。
* @throws Exception
*/
public static void test_11() throws Exception {
CompletableFuture<Long> futures = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (1 > 2) {
int c = 12 / 0; //抛异常
}
System.out.println("run end.......");
return 1L;
}).thenApply(new Function<Long, Long>() {
@Override
public Long apply(Long aLong) {
System.out.println("当前任务的事务~~~~");
long res = aLong * 5;
System.out.println("当前的结果~~~" + res);
return res;
}
});
}
/**
* handle 方法
* handle 是执行任务完成时对结果的处理。
* handle 方法和 thenApply 方法处理方式基本一样。不同的是 handle 是在任务完成后再执行,还可以处理异常的任务。thenApply 只可以执行正常的任务,任务出现异常则不执行 thenApply 方法。
* @throws Exception
*/
public static void test_12() throws Exception {
CompletableFuture<Integer> futures = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
int i=10/1;
return 3;
}
}).handle(new BiFunction<Integer, Throwable, Integer>() {
@Override
public Integer apply(Integer integer, Throwable throwable) {
int result=1;
if(null==throwable){
result=integer*2;
System.out.println("乘以2之后的结果:"+result);
}else{
System.out.println(throwable.getMessage());
}
return result;
}
});
//只阻塞future.whenComplete 不阻塞,future.whenCompleteAsync
long results = futures.get();
System.out.println(results);
}
/**
*thenAccept 消费处理结果,接收任务的处理结果,并消费处理,无返回结果。
* 该方法只是消费执行完成的任务,并可以根据上面的任务返回的结果进行处理。并没有后续的输错操作。
* @throws Exception
*/
public static void test_13() throws Throwable {
CompletableFuture<Void> futures = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
int i=10/1;
return 3;
}
}).thenAccept(new Consumer<Integer>() {
@Override
public void accept(Integer integer) {
integer=integer+3;
System.out.println(""+integer);
}
});
//只阻塞future.whenComplete 不阻塞,future.whenCompleteAsync
System.out.println( futures.get());
}
/**
* 该方法同 thenAccept 方法类似。不同的是上个任务处理完成后,并不会把计算的结果传给 thenRun 方法。只是处理玩任务后,执行 thenAccept 的后续操作。
* @throws Throwable
*/
public static void test_14() throws Throwable {
CompletableFuture<Void> integerCompletableFuture = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
int i = 10 / 1;
return 3;
}
}).thenRun(new Runnable() {
@Override
public void run() {
System.out.println("thenRun---》执行中。。。");
}
});
//只阻塞future.whenComplete 不阻塞,future.whenCompleteAsync
System.out.println( integerCompletableFuture.get());
}
/**
* thenCombine 会把 两个 CompletionStage 的任务都执行完成后,把两个任务的结果一块交给 thenCombine 来处理。
* @throws Exception
*/
private static void thenCombine() throws Exception {
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(new Supplier<String>() {
@Override
public String get() {
return "hello";
}
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(new Supplier<String>() {
@Override
public String get() {
return "world";
}
});
CompletableFuture<String> result = future1.thenCombine(future2, new BiFunction<String, String, String>() {
@Override
public String apply(String t, String u) {
return t+" "+u;
}
});
System.out.println(result.get());
}
/**
* 当两个CompletionStage都执行完成后,把结果一块交给thenAcceptBoth来进行消耗
* @throws Exception
*/
private static void thenAcceptBoth() throws Exception {
CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("f1="+t);
return t;
}
});
CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("f2="+t);
return t;
}
});
System.out.println(f1.get());
System.out.println(f2.get());
f1.thenAcceptBoth(f2, new BiConsumer<Integer, Integer>() {
@Override
public void accept(Integer t, Integer u) {
System.out.println("f1="+t+";f2="+u+";");
}
});
}
/**
* applyToEither 方法
* 两个CompletionStage,谁执行返回的结果快,我就用那个CompletionStage的结果进行下一步的转化操作。
* @throws Exception
*/
private static void applyToEither() throws Exception {
CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("f1="+t);
return t;
}
});
CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("f2="+t);
return t;
}
});
f2.get();
f1.get();
CompletableFuture<Integer> result = f1.applyToEither(f2, new Function<Integer, Integer>() {
@Override
public Integer apply(Integer t) {
System.out.println(t);
return t * 2;
}
});
System.out.println("applyToEither--->"+result.get());
}
/**
* acceptEither 方法
* 两个CompletionStage,谁执行返回的结果快,我就用那个CompletionStage的结果进行下一步的消耗操作
* @throws Exception
*/
private static void acceptEither() throws Exception {
CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("f1="+t);
return t;
}
});
CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("f2="+t);
return t;
}
});
f1.get();
f2.get();
f1.acceptEither(f2, new Consumer<Integer>() {
@Override
public void accept(Integer t) {
System.out.println(t);
}
});
}
/**
* runAfterEither 方法
* 两个CompletionStage,任何一个完成了都会执行下一步的操作(Runnable)
* @throws Exception
*/
private static void runAfterEither() throws Exception {
CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("f1="+t);
return t;
}
});
CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("f2="+t);
return t;
}
});
f1.runAfterEither(f2, new Runnable() {
@Override
public void run() {
System.out.println("上面有一个已经完成了。");
}
});
}
/**
* runAfterBoth
* 两个CompletionStage,都完成了计算才会执行下一步的操作(Runnable)
* @throws Exception
*/
private static void runAfterBoth() throws Exception {
CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("f1="+t);
return t;
}
});
CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("f2="+t);
return t;
}
});
f1.get();
f2.get();
f1.runAfterBoth(f2, new Runnable() {
@Override
public void run() {
System.out.println("上面两个任务都执行完成了。");
}
});
}
/**
* thenCompose 方法
* thenCompose 方法允许你对两个 CompletionStage 进行流水线操作,第一个操作完成时,将其结果作为参数传递给第二个操作。
* @throws Exception
*/
private static void thenCompose() throws Exception {
CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
int t = new Random().nextInt(3);
System.out.println("1");
return t;
}).thenCompose(new Function<Integer, CompletionStage<Integer>>() {
@Override
public CompletionStage<Integer> apply(Integer param) {
return CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
int t = param *2;
System.out.println("t2="+t);
return t;
}
});
}
});
}
private static void thenCompose1() throws Exception {
CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
int t = new Random().nextInt(3);
System.out.println("1");
return t;
}).thenCompose(param -> CompletableFuture.supplyAsync(() -> {
int t = param *2;
System.out.println("t2="+t);
return t;
}));
}
ref:https://www.jianshu.com/p/6bac52527ca4