CompletableFuture为什么会出现
CompletableFuture源码分析
CompletionStage作用
CompletableFuture
CompletableFuture的使用
无返回值
package com.cheng;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* 无返回值
*/
public class CompletableFutureTest {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(3);
CompletableFuture.runAsync(()->{
System.out.println(Thread.currentThread().getName());
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, pool);
pool.shutdown();
}
}
有返回值
package com.cheng;
import java.util.concurrent.*;
/**
* 有返回值
*/
public class CompletableFutureTest2 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(3);
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName());
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello";
}, pool);
System.out.println(completableFuture.get());
pool.shutdown();
}
}
CompletableFuture通用功能介绍
CompletableFuture是Future的增强版,可以减少阻塞和轮询,也可以传入回调对象,当异步任务完成或者发生异常时,自动调用回调对象的回调方法!!
CompletableFuture中的回调函数whenComplete和exceptionally
package com.cheng;
import java.util.concurrent.*;
/**
* 有返回值
*/
public class CompletableFutureTest2 {
public static void main(String[] args) {
test3();
}
/**
* CompletableFuture的一般用法
*/
public static void test3() {
//使用自定义的线程池
ExecutorService pool = Executors.newFixedThreadPool(3);
try{
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + " ---come in!");
int i = ThreadLocalRandom.current().nextInt(10);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return i;
}, pool).whenComplete((v, e) -> { // 程序运行正常时的回调函数 其中v为返回值,e为传递的异
if (e == null) { // 异常为空说明程序正常运行,打印生成的随机数
System.out.println("计算完成,随机数字是 " + v);
}
}).exceptionally(e -> { // 程序运行异常时的回调函数
System.out.println(e.getCause() + e.getMessage());
return null;
});
System.out.println("1秒钟后出结果!");
} catch (Exception e){
} finally {
pool.shutdown();
}
}
}