想知道一个completablefuture是否可以在创建它的线程中运行。您可能会问为什么我需要这样做,因为completablefuture用于异步编程。原因是我有一些异步任务,有些任务要在生成线程中运行,以便可以使用allOf等并在代码中保持一致性]
是的,完全有可能。这是一个示例程序,用于演示
private static Executor 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