参考:搞定 CompletableFuture,并发异步编程和编写串行程序还有什么区别?你们要的多图长文
java的future在执行get时是会阻塞的,直到拿到返回结果才会执行后面的逻辑,这和js中的axiso异步不同,并不是我们想要的:
public class FutureDemo1 {
public static void main(String[] args) {
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 10,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(), threadFactory);
FutureRunnable runnable = new FutureRunnable();
Future<?> submit = threadPoolExecutor.submit(runnable);
try {
submit.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
System.out.println("程序结束");
while (true) {
if (Thread.currentThread().isInterrupted()) {
threadPoolExecutor.shutdown();
break;
}
}
}
}
class FutureRunnable implements Runnable {
@Override
public void run() {
try {
System.out.println("程序正在运行");
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
throw new RuntimeException("报错了!");
}
}
使用了CompletableFuture后:
public class FutureDemo2 {
public static void main(String[] args) {
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 10,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(), threadFactory);
FutureRunnable2 runnable2 = new FutureRunnable2();
CompletableFuture.runAsync(runnable2, threadPoolExecutor)
.whenComplete((aVoid, throwable) -> System.out.println("程序A结束"))
.exceptionally(throwable -> {
throwable.printStackTrace();
runnable2.flg = false;
return null;
});
System.out.println("我在A执行后,A报错前执行");
while (true) {
if (!runnable2.flg) {
threadPoolExecutor.shutdown();
break;
}
}
}
}
class FutureRunnable2 implements Runnable {
volatile boolean flg = true;
@Override
public void run() {
try {
System.out.println("程序A正在运行");
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
throw new RuntimeException("A报错了!");
}
}