Is SwingWorker the only way?

六眼飞鱼酱① 提交于 2019-12-24 16:19:02

问题


I have found that in order to keep Java GUIs (using Swing) responsive the only way is to use the SwingWorker class, as opposed to java.lang.Thread. Is SwingWorker truly the only way when it comes multithreaded GUI based desktop apps? Are there any good alternatives? Rarely can I configure the Thread class to do what I want to do, but SwingWorker usually works, if sometimes in a cumbersome way.


回答1:


SwingWorker is nothing but a thin convenience API around Thread. Therefore it is definitely possible to use Thread without SwingWorker. The main point is that Swing is not thread-safe and any actions you perform on Swing objects must happen on the Event Dispatch Thread. This is the fundamental obstacle, and SwingWorker tries to help you overcome it a bit more conveniently.




回答2:


The alternative is a continuation using EventQueue.invokeLater(), but SwingWorker has important advantages:

  • It synchronizes granular access to data shared between itself and the EDT.

  • It provides property change support for progress indication.

  • It implements the Future interface.

See also Worker Threads and SwingWorker for details.




回答3:


Multithreading in GUI application is difficult to implement since there can be so many actions that trigger actions. A good explanation of why is this a "failed dream" can be found here Multithreaded toolkits: A failed dream.. For solutions to your problem, read this article on concurrency in swing: Concurrency in Swing

Depending on your duration of the action you can go with SwingUtilities.invokeLater() or make a SwingWorker for tasks that take a long time to complete and run in background. You must use this classes or else you may be in situations where a thread will block your entire application and may seem unresponsive to the user.




回答4:


Another option, most suitable for repetitive tasks, is javax.swing.Timer (it can be used for one-shot tasks as well).



来源:https://stackoverflow.com/questions/21905494/is-swingworker-the-only-way

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