Threads And AWT/Swing
In Java programs with GUIs that use Swing and/or the AWT, the AWT event handler runs in its own thread. Developers must be careful to not tie up this GUI thread performing time-consuming work, because it is responsible for handling user events and redrawing the GUI. In other words, the program will appear frozen whenever the GUI thread is busy. Swing callbacks, such as Mouse Listeners and Action Listeners are all notified (by having appropriate methods called) by the Swing thread. This approach means that any substantial amount of work the listeners are to do must be performed by having the listener callback method spawn another thread to do the work. The goal is to get the listener callback to return quickly, allowing the Swing thread to respond to other events.
If a Swing thread is running asynchronously, responding to events and repainting the display, how can other threads modify Swing state safely? As I just mentioned, Swing callbacks run in the Swing thread; therefore, they can safely modify Swing data and draw to the screen.
But
what about other changes that don't happen as a result of a Swing
callback? Having a non-Swing thread modify Swing data is not thread
safe. Swing provides two methods to solve this problem: invokeLater()
and invokeAndWait()
. To modify the Swing state, simply call either of these methods, passing a Runnable
object that does the proper work. Because Runnable
objects are usually their own threads, you might think that this object
is spawned off as a thread to execute. In fact, this is not the case,
as that too would not be thread safe. Instead, Swing puts this object
in a queue and executes its run method at an arbitrary point in the
future. This makes the changes to Swing state thread safe.
View Writing Multithreaded Java Applications Discussion
Page: 1 2 3 4 5 6 7 Next Page: Wrapup And Resources