user1264737
user1264737

Reputation: 13

Java Threading - Swing app

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

Upvotes: 0

Views: 244

Answers (3)

AlexR
AlexR

Reputation: 115328

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!

Upvotes: 0

Abhishek Choudhary
Abhishek Choudhary

Reputation: 8385

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.

Upvotes: 1

assylias
assylias

Reputation: 328608

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.

Upvotes: 0

Related Questions