When you run this example, you will see that when a button is pressed, it changes colors and is
deactivated while the work is being done. However, you can press as many buttons as you like,
one right after the other without waiting for the first to complete.
window. This starts up an event thread that then enters the event loop and waits for input. When
you push a button, the callback ThreadButtonListner.actionPerformed() runs,
deactivates the button, changes its colors, and (optionally) creates a new thread (T2) to run the
work function [DoWorker.run()].
The event thread then returns to the event loop. You press another button and the cycle repeats. In
the meantime (back at the ranch), the new thread has started up and begun running. With our
second push, a third thread (T3) has started up, just like T2. After a few seconds, T2 completes its
work and calls invokeLater[new DidWorker()] and exits.
The event thread sees the invokeLater request and runs the method DidWorker.run(). That
function sets the button back to the original colors and reactivates the button. Now only T3 is
running. Soon it will complete and repeat the actions of T2. In this fashion, the event loop is
always active and the Swing calls are made only from the event thread.
If you push the "Threaded" button, the program will not use threads, but rather, it will do all the
work directly in the event thread. And the program will slow down a lot.
Notice that we are using a runnable as the item of work to be performed and we are going to allow
it to be run either in a new thread or in the event thread itself. This is one of the reasons that
runnables are good.
Displaying Things for a Moment (Memory.java)
Sometimes you would like an applet (or any windowing program) to display something for the
user to see for a short time, then continue on to do other things. In their excellent topic Java by
Example (see Appendix B), Jackson and McClellan show a little program that tests human
memory. We wrote an abbreviated version of it. It shows four colored boxes: red, blue, green,
yellow (Figure 17-2). When the game starts, it makes one of those boxes brighter for a couple
seconds, then dims it again. Next it chooses another (at random) and brightens that for a couple
Figure 17-2. The Memory Game
Search WWH :