img
. . . .
Several other methods are also thread-safe and may be called from any thread, including
JTextComponent.setText(), JTextArea.insert(), JTextArea.append(),
JTextArea.replaceRange(), JComponent.repaint(), and
JComponent.revalidate(). You may also add and remove event listeners from any thread.
The listener methods will, of course, run in the event dispatch thread. You may also create
components, set their properties, and add them to containers as long as they are not yet realized.
Once realized [via show(), setVisible(), or pack()] you cannot manipulate them any
longer. You will probably never use any of the latter thread-safe methods, as it is normally
possible to do everything from either the main thread or via invokeLater().
The result of this design is that the window thread (the one running the event loop) spends the vast
majority of its time blocked in read, waiting for an event. This is good. You want to do your main
computing in another thread. The problem that arises is that some button might invoke a long-
running method, freezing the GUI until it completes.
So you can have the callback function spawn a new thread to handle the calculation and the
callback can return immediately. This way, the GUI is still active and the calculation is performed
in the new thread. When the calculation is complete, the thread can then request updates to the
windows to be done by calling invokeLater() (Figure 11-4).
Figure 11-4. ThreadedSwing Window Example
This is the same technique that is used in the native window toolkits in UNIX. As Motif has no
"invokeLater()"-style function, C programmers simply send an event directly from the thread
to the event loop using XCreateEvent(), causing the event loop to run the callback for that
event.
Code Example 11-1 is from the program ThreadedSwing (see the complete code in Threads and
Windows) and shows the callbacks, the function that runs when you push a button (which just
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home