Threads in Java Swing, overview of three approaches in an application
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();
Th开发者_Go百科anks!
#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.
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:
A Swing programmer deals with the following kinds of threads:
- Initial threads, the threads that execute initial application code.
- The event dispatch thread, where all event-handling code is executed. Most code that interacts with the Swing framework must also execute on this thread.
- Worker threads, also known as background threads, where time-consuming background tasks are executed.
精彩评论