Calling repaint in multiple threads?

ぐ巨炮叔叔 提交于 2019-12-25 03:39:31

问题


Since a few days I've been playing a bit with a small game in java.

Does it hurt java swing when 2 threads call repaint() at the same time?

I ask this because i have a paint thread, which calls repaint at a certain interval. In addition i call repaint when the player executes an action. Both repaint calls will repaint the same custom JPanel.

In theory repaint can then be called by 2 threads at the same time.


回答1:


Actually repaint() can be called in the same time in this case. But it is not a problem.

Actually methods like repaint(), revalidate() are safe to use within any thread. Those methods actually queue requests to EDT(Event Dispatch Thread) to call paint() and validate(). So if you call repaint() many times using different threads, it will queue the request to call paint() method..

Click here for more about EDT.

It is not safe to call paint() method, without using EDT. (Better if you don't call forever.) But calling repaint() at same time using different threads will not be a problem..




回答2:


You can't. All GUI updates need to be done by the same UI thread. This is not only true for Swing application but also for other UI frameworks and in other languages. What you might be able to do is prepare the update of the UI in a different thread and then delegate the last step to the UI-Thread, which updates the GUI.



来源:https://stackoverflow.com/questions/33015382/calling-repaint-in-multiple-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!