完整的未来等待UI-Thread的UI-Thread?
Java 8的承诺实现,即completableFuture
,同时提供了thepply(...)
和get()
方法。
其中get()
在必要时等待承诺完成,然后返回其结果。
现在假设我们使用thenapply(...)
(或thenapplyasync(...)
)链接一些代码以在UI-Thread
上运行 (请参阅stackoverflow.com/<
什么是行为,如果我们在UI-Thread中调用get() - 锁还是无限环?
我以前正在使用QT框架,在此取决于我们如何实现服务员(dispatch-ui-events vs sleep
),可以在同一ui-thread中等待ui-thread(例如,整个视图恢复了现场,而没有从我的代码中返回)。
但是我不确定Java是否支持这一点。
Java 8's promise implementation, namely CompletableFuture
, provides both thenApply(...)
and get()
methods.
Where get()
waits if necessary for the promise to complete, and then returns its result.
Now assume we use thenApply(...)
(or thenApplyAsync(...)
) to chain some code to run on UI-thread
(see stackoverflow.com/difference between thenApply and thenApplyAsync).
What is the behaviour if we call get()
in the UI-thread as well, like does Java handle this case somehow, or can it result to a so-called dead-lock or infinite-loop?
I previously was using Qt framework, where depending on how we did implement waiter (dispatch-UI-events vs sleep
), it was possible to wait for UI-thread from within same UI-thread (for example, the entire view came back to live, and that without returning from my code).
But I am not sure if Java even supports that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
调用
get()
阻止当前线程,直到结果可用。如果那是UI事件调度程序线程,则您的应用程序的UI变得无响应(阻止)。与QT不同,Java不支持手动处理UI事件,这意味着一旦您在UI-thread上等待,其他任何其他东西都无法在UI-Thread上运行(直到服务员返回)。
此外,不要攻击“
thenapply(...)
”方法可以在UI-Thread上运行内容,因为有一个更好的解决方案,我的意思是使用theApplyasync(...)
将executor
作为参数的版本。上述executor
是一种功能接口,具有一种方法,void execute(runnable命令)
。您可以使用eventqueue :: InvokElater
(或其包装器swingutilities.invokelater
)。然后,它将在事件调度程序线程(又称UI-Thread)上执行代码。Calling
get()
blocks the current thread until the result is available. If that's the UI event dispatcher thread then your application's UI becomes unresponsive (blocked).And unlike Qt, Java does not support manually processing the UI events, meaning once you wait on the UI-thread nothing else can run on UI-thread (until waiter returns).
In addition, don't hack "
thenApply(...)
" method to run things on UI-thread, as there's a better solution, I mean use thethenApplyAsync(...)
version which takes anExecutor
as parameter. SaidExecutor
is a functional interface with one method,void execute(Runnable command)
. You can useEventQueue::invokeLater
(or its wrapperSwingUtilities.invokeLater
) for that. It will then execute the code on the event dispatcher thread (aka UI-thread).