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!
#1 and #2 are the same. You should use number #1 since that's the well-known part of the API.
Whether you use #1 or #3 depends on the following:
Is it making changes to the user interface or its backing models? If yes, use #1.
Is it a long-running task: If yes, use #3.
If it is a long-running task that will eventually modify the user interface or its backing model, perform the long running task in a separate thread, and then call incokeLater to update the user interface.
Furthermore, instead of creating a new thread every time, use an ExecutorService so you can reuse threads.
It can get a little bit more complicated, for example, if you're currently in the event thread (ie: in an ActionListener.actionPerformed()
, then you don't need to (as in shouldn't) call invokeLater, but the gist of it is up there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With