CompletableFuture源码详解之java.util.concurrent.CompletableFuture#runAsync(java.lang.Runnable)
时间: 2023-10-13 20:15:47 浏览: 101
CompletableFuture是Java 8中新增的一个类,它提供了一种异步编程的方式,可以方便地进行异步操作和线程间的通信。其中,runAsync方法是CompletableFuture中的一个静态方法,用于执行一个Runnable任务,并返回一个CompletableFuture对象,其中不包含任何返回值。
下面我们来看一下runAsync方法的源码实现:
```java
public static CompletableFuture<Void> runAsync(Runnable runnable) {
return asyncRunStage(asyncPool, runnable);
}
private static CompletableFuture<Void> asyncRunStage(Executor e, Runnable f) {
if (f == null) throw new NullPointerException();
CompletableFuture<Void> d = new CompletableFuture<Void>();
e.execute(new AsyncRun(d, f));
return d;
}
static final class AsyncRun implements Runnable {
final CompletableFuture<Void> d; final Runnable f;
AsyncRun(CompletableFuture<Void> d, Runnable f) { this.d = d; this.f = f; }
public void run() {
try {
f.run();
d.complete(null);
} catch (Throwable ex) {
d.completeExceptionally(ex);
}
}
}
```
从代码中可以看出,runAsync方法会调用asyncRunStage方法,将任务和线程池传入异步执行。
在asyncRunStage方法中,首先会判断参数是否为空,如果为空就抛出NullPointerException异常。
接下来,会创建一个CompletableFuture对象d,并将它和任务f封装到AsyncRun对象中。
然后,通过线程池e执行AsyncRun对象,即执行任务f,并将结果存放到CompletableFuture对象d中。
如果任务f执行成功,就调用CompletableFuture对象的complete方法将结果设置为null;如果任务f执行失败,就调用CompletableFuture对象的completeExceptionally方法将异常信息设置到CompletableFuture对象中。
最后,异步执行过程结束,返回CompletableFuture对象d。
总结一下,CompletableFuture的runAsync方法通过将任务封装到AsyncRun对象中,并异步执行任务,最后将结果存放到CompletableFuture对象中,实现了异步编程和线程间通信。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)