Java异步处理CompletableFuture
异步处理简单来说就是另起一个线程处理,使程序不至于阻塞到某一步,导致后续代码无法执行。
异步处理的方法有很多,懒的话直接new Thread(() -> {}).start();
,也不是不行。但是这样会让自己显得很low,不能向别人装13。再进一步,其实可以用线程池来管理,但是各种线程之间的通信也很麻烦,还要注意线程安全的问题。jdk1.8提供了CompletableFuture类,扩展了Future接口,可以帮助我们简化异步处理。
一个无返回值的异步处理过程:
public static void main(String[] args) throws InterruptedException {
CompletableFuture.runAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread() + "-----" +System.currentTimeMillis());
});
System.out.println(Thread.currentThread() + "-----" +System.currentTimeMillis());
// 保证主线程不早于异步线程结束
Thread.sleep(10000);
}
打印结果:
Thread[main,5,main]-----1582874573581
Thread[ForkJoinPool.commonPool-worker-3,5,main]-----1582874574584
从结果看,异步方法中的延迟1000ms,并没有影响到主线程的运行。
主线程中的sleep(10000),主要是防止主线程过早结束,因为CompletableFuture默认使用的是ForkJoinPool,此线程池创建的线程为守护线程,如果非守护线程全部结束,其也会自动结束。
上面演示的为没有返回值的异步,下面演示有返回值的异步:
public static void main(String[] args) throws InterruptedException {
CompletableFuture<Long> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long l = System.currentTimeMillis();
System.out.println(Thread.currentThread() + "-----" + l);
// 返回当前时间
return l;
});
try {
// 获取异步执行结果
System.out.println(future.get());
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread() + "-----" + System.currentTimeMillis());
Thread.sleep(10000);
}
运行结果:
Thread[ForkJoinPool.commonPool-worker-3,5,main]-----1582875356876
1582875356876
Thread[main,5,main]-----1582875356914
根据结果看,异步方法执行了,future.get()阻塞了,获取到结果后继续执行后续任务。
因为上面说了,CompletableFuture实现了Future接口,当然可以用Future的get方法获取结果,但是我们都知道,Future的get方法是会阻塞的,这对于我们异步执行没什么作用啊。对了,因为CompletableFuture的正确用法不是直接使用get阻塞来获取结果。
下面演示非阻塞获取异步结果:
public static void main(String[] args) throws InterruptedException {
CompletableFuture