I’m using the code bellow in a desktop swing application, and I don’t have much expertise
with threads, because I’m a casual web programmer and deal with swing isn’t my candy…
I want to know if have better approach to control my 3 tasks and I need running them in parallel one for thread in my app.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
task 1
}
});
Runnable r;
r = new Runnable() {
public void run() {
task 2
}
};
EventQueue.invokeLater(r);
Thread worker = new Thread() {
public void run() {
task 3
}
};
worker.start();
Thanks!
What are you trying to do? Does your thread operate in the Swing GUI or is it independent of the GUI?
You should use
invokeLater()if the thread is doing something with the Swing user interface, because that can only be done from the Event Dispatch Thread. Swing is single-threaded. (Your task 1 and 2)If you are doing something completely in the background e.g. writing a large XML-file, that can be done in a background thread. (Your task 3) But you can still communicate with the Swing GUI using
invokeLater().Another alternative is if you want to run a thread regularly, e.g. every 5th minute, you can use a TimerTask. Or if it’s independent of the Swing GUI java.util.TimerTask.
Concurrency in Swing might be worth reading: