运行一个简单的异步阶段
这个例子创建一个一个异步执行的阶段:
static void runAsyncExample() {
CompletableFuture cf = CompletableFuture.runAsync(() -> {
assertTrue(Thread.currentThread().isDaemon());
randomSleep();
});
assertFalse(cf.isDone());
sleepEnough();
assertTrue(cf.isDone());
}
通过这个例子可以学到两件事情:
CompletableFuture的方法如果以Async结尾,它会异步的执行(没有指定executor的情况下), 异步执行通过ForkJoinPool实现, 它使用守护线程去执行任务。注意这是CompletableFuture的特性, 其它CompletionStage可以override这个默认的行为。
-------------------------------------------------------------------
runAsync 方法不支持返回值。
//无返回值
public static void runAsync() throws Exception {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
System.out.println("run end ...");
});
future.get();
}

本文介绍了如何使用CompletableFuture的runAsync方法创建一个异步执行的阶段,解释了其默认行为——通过ForkJoinPool使用守护线程,并指出runAsync方法不支持返回值。通过实例演示了异步执行的特点和限制。
974

被折叠的 条评论
为什么被折叠?



