场景
接口执行较慢,直接采用异步处理,复杂的业务流程由异步线程去做。伪代码如下:
public static void main(String[] args) throws InterruptedException, ExecutionException {
CompletableFuture.runAsync(() ->{
try {
method();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
System.out.println("main +++++++++++++++++++++++");
}
private static void method() throws InterruptedException {
System.out.println("start==================");
Thread.sleep(10000);
System.out.println("end====================");
}
控制台打印结果如下:
"C:\Program Files\Java\jdk1.8.0_261\bin\java.exe" "-javaagent:D:\Soft\IntelliJ ...
cn.net.hylink.data.service.imple.demo
main +++++++++++++++++++++++
start==================
Process finished with exit code 0
发现并没有打印 System.out.println(“end====================”);
原因
代码中通过Thread.sleep(10000),导致异步线程阻塞了10s,主线程执行完,异步线程挂了。。。为啥挂了,等有时间看下,或者评论告诉我。
解决
1)使用使用CompletableFuture的get方法来等待异步任务完成并获取结果
代码如下:
public static void main(String[] args) throws InterruptedException, ExecutionException {
CompletableFuture<Void> future = CompletableFuture.runAsync(() ->{
try {
method();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
System.out.println("main +++++++++++++++++++++++");
future.get();
}
private static void method() throws InterruptedException {
System.out.println("start==================");
Thread.sleep(10000);
System.out.println("end====================");
}
控制台打印结果如下:
"C:\Program Files\Java\jdk1.8.0_261\bin\java.exe" "-javaagent:D:\Soft\IntelliJ ...
main +++++++++++++++++++++++
start==================
end====================
Process finished with exit code 0
2) 指定线程池
代码如下:
private static final ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
public static void main(String[] args) throws InterruptedException, ExecutionException {
CompletableFuture.runAsync(() ->{
try {
method();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
},cachedThreadPool);
System.out.println("main +++++++++++++++++++++++");
}
private static void method() throws InterruptedException {
System.out.println("start==================");
Thread.sleep(10000);
System.out.println("end====================");
}
控制台打印结果如下:
"C:\Program Files\Java\jdk1.8.0_261\bin\java.exe" "-javaagent:D:\Soft\IntelliJ ...
main +++++++++++++++++++++++
start==================
end====================
Process finished with exit code 0
补充
异步线程抛异常,外部try{}catch(){}捕捉不到。
有错误欢迎指正,有问题欢迎提问。