有可能在创建它的同一个线程中运行一个可完成的future吗



想知道是否可以在创建可完成未来的线程中运行它。您可能会问我为什么需要这样做,因为completablefuture是用于异步编程的。原因是我有一些异步任务和一些我想在生成线程中运行的任务,这样我就可以使用allOf等并保持代码的一致性

当你说你想知道"一个可完成的未来是否可以在创建它的线程中运行"时,你表现出了错误的心态。CompletableFuture未运行。CompletableFuture只是封装了一个值或异常,它最多可以设置一次,我们称之为完成

API提供了很多方法来安排完成尝试,可能是异步的,但你不应该因为决定如何完成而分心

异步完成有简单的替代方案:

CompletableFuture<String> f = CompletableFuture.completedFuture("hello");

创造一个立即完成的未来。Java 9添加了failedFuture以支持创建一个立即异常完成的未来。

您还可以在同一个线程中轻松创建一个稍后要完成的未来:

CompletableFuture<String> f = new CompletableFuture<>();
// arbitrary actions
f.complete("hello");

您也可以使用带有执行器的工厂方法,立即在启动线程中运行操作:

CompletableFuture<String> f
= CompletableFuture.supplyAsync(() -> "hello", Runnable::run);

CompletableFuture<String> f
= CompletableFuture.supplyAsync(() -> {
if(Math.random() > 0.5) throw new IllegalStateException();
return "hello";
}, Runnable::run);

以演示与调用CCD_ 4或创建立即完成的未来的区别。

当然,这些可能性可以与其他功能相结合,如allOf:

CompletableFuture<String> a = new CompletableFuture<>();
CompletableFuture<String> b = new CompletableFuture<>();
CompletableFuture<String> c = new CompletableFuture<>();
CompletableFuture.allOf(a, b, c).whenComplete((__, t) -> {
if(t != null) System.err.println("failed with "+t);
else System.out.println("all completed "+a.join()+", "+b.join()+", "+c.join());
});
System.out.println("step 1");
a.complete("foo");
System.out.println("step 2");
b.complete("bar");
System.out.println("step 3");
c.complete("baz");

是的,完全可能。这是一个演示的示例程序

private static ExecutorService executor = Executors.newSingleThreadExecutor();
public static void main(String[] args)
{
executor.execute(() -> {
System.out.println("Scheduling " + Thread.currentThread().getName());
CompletableFuture.supplyAsync(() -> {
System.out.println("Sleeping " + Thread.currentThread().getName());
try {
Thread.sleep(2000);
}
catch (InterruptedException e) {}
System.out.println("Returning " + Thread.currentThread().getName());
return 123;
},
executor)
.thenAccept(retValue -> System.out.println("Got value " + retValue + " " + Thread.currentThread().getName()));
});
}

输出

Scheduling pool-1-thread-1
Sleeping pool-1-thread-1
Returning pool-1-thread-1
Got value 123 pool-1-thread-1

最新更新