gpt4 book ai didi

java - 如何从 SupplySync 返回对象而不阻塞主线程?

转载 作者:行者123 更新时间:2023-12-02 01:54:36 25 4
gpt4 key购买 nike

我试图在不阻塞主线程的情况下返回一个 future 对象。在这样做时,我尝试使用 SupplyAsync 方法异步运行线程,但在使用 get() 函数获取所需对象时主线程被阻塞

final CompletableFuture<RequiredObject> future =CompletableFuture.supplyAsync(() -> {`RequiredObject ro = new RequiredObject;
//some code
return ro;
},executor);

future.get(); //this blocks the main thread

执行线程阻塞主线程

最佳答案

您可以使用 getNow(T valueIfAbsent)

Returns the result value (or throws any encountered exception) if completed, else returns the given valueIfAbsent.

关于java - 如何从 SupplySync 返回对象而不阻塞主线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57406443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com