JavaFX应用程序线程如何工作? [英] How JavaFX application thread works?

查看:249
本文介绍了JavaFX应用程序线程如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了Java FX应用程序线程的问题。这是一个伪代码:

I have a problem with Java FX application thread. Here is a pseudo-code:

showMenu();
//Contoller which waits for action(pressing button)...
showLoadingPic();
Thread.sleep(2000);
showMap();

问题是睡眠发生在showMenu()中显示的窗口中,showLoadingPic()是完全没有显示,并且在showMap()的结束窗口显示。

The problem is that the sleep occurs in window which is displayed in showMenu(), showLoadingPic() is not shown at all, and at the end window in showMap() is shown.

showLoadingPic中的场景有一个进度条,运行2秒,这与了Thread.sleep(2000)。

The scene in showLoadingPic has a progress bar which runs 2 secs which is the same time as Thread.sleep(2000).

所以看起来javafx应用程序线程块showLoadingPic()和showLoadingPic()在后台运行。

So it seems like javafx application thread blocks showLoadingPic() and showLoadingPic() runs at background.

有人可以帮我解决这个问题吗?

Can somebody help me to fix this??

提前谢谢你!

推荐答案

有一个Java FX事件调度线程,它处理所有与GUI相关的任务。您必须更新此线程中的所有UI组件。
长时间运行的任务,比如 Thread.sleep 永远不应该在这个线程中执行,因为windows会挂起,GUI将冻结

There is a Java FX event dispatch thread, which handle all GUI-related tasks. You must update all UI components in this thread. Long-running tasks, like Thread.sleep should never be executed in this thread, since windows will hang, and the GUI will be frozen.

执行应用程序主线程中的所有代码,并通过调用 Platform.runLater

Execute all your code in the application main thread, and perform only GUI tasks in JavaFX thread, by calling Platform.runLater.

有关此主题的参考资料:

References on this topic:

  • Concurrency in JavaFX, from Oracle
  • Related SO question

这篇关于JavaFX应用程序线程如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆