Java Threading - Swing app

余生颓废 提交于 2019-12-12 02:33:41

问题


I'm trying to learn how to thread a class (specifically a method in a class) and I've come across Thread() and SwingWorker(). This is a swing application. Which should I choose and why? Also, is there some generic way to add implementation for threading to existing methods?

Thanks


回答1:


SwingWorker is mainly for executing background processes in Java Swing means UI based application , like on pressing a Button in a UI , you want some long process to happen in Background. Thread is normally used to multitasking in Java Programs like executing two operations in a time kind of stuffs. Thread can be implemented from Runnable interface as well as inherited from thread Class. Check Oracle Java Docs.




回答2:


Using Swingworkers would probably make your like easier because it is meant to do exactly what you need. There is a good tutorial on Oracle's website that would get you started. In essence, in a Swing application, you need to make sure that:

  • Anything that interacts with the GUI runs in the EDT (Event Dispatch Thread)
  • Long tasks do not run on the EDT because if they do they will freeze the GUI while your computation is running

Swingworkers handle those 2 things very well.




回答3:


Class Thread is a basic piece you need to create threads. JDK provides either "low level" API (take a look on class Thread, interface Runnable, synchoronized keyword, methods wait(), notify()) or higher level API (SwingWorker, Timer, executors framework).

There is a lot of tutorials in web. Learn basics first. Read javadoc of Thread, find some examples, play with them. Then go through Timer and SwingWorker. It will be simple. Then, when you understand how is it working take your time to study executors, thread pools etc.

Happy threading!



来源:https://stackoverflow.com/questions/9672081/java-threading-swing-app

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