Java Reference
In-Depth Information
20.2.2
Avoiding the blocking
The solution to the above problem is not to run the lengthy lengthyWork method
in the event thread but in a separate thread. The event thread merely starts this
other thread. It then immediately processes the next event in the queue, while
the lengthy job is running in the other thread in parallel.
In our example we define an internal class WorkerThread which is derived from
Thread . When a thread is started then its method run is executed. Therefore, all
the instructions the thread should execute should be placed here 2 .Inour example
the lengthy job is placed there.
Now, method actionPerfomed does not call lengthyWork but it creates an
instance worker of WorkerThread and starts it by calling worker.start() . After
this, actionPerfomed finishes. Even though actionPerfomed is run in the event
thread, it does so only for the time needed to start the worker thread. It does not
block the processing of further events. The menu rolls back immediately after we
selected the menu item 'Start'. Also the text of the label changes every half second.
On the console we can now see that the lengthy job is performed in neither
the main nor the event thread. Instead it runs in a thread called 'Thread-1' which
is the internal name for our worker thread. As the lengthy operation now runs
in a separate thread, the event thread can process the requests to repaint the
frame or label as soon as they come in. Below, a listing of the console output is
shown:
Running in thread main
WorkerThread1: started as Thread-1
Working 0
Running in thread Thread-1
Working 1
Running in thread Thread-1
Working 2
Running in thread Thread-1
Working 3
Running in thread Thread-1
Working 4
Running in thread Thread-1
Working 5
Running in thread Thread-1
Working 6
Running in thread Thread-1
Working 7
Running in thread Thread-1
Working 8
Running in thread Thread-1
Working 9
2
As for listener methods such as actionPerformed , this formulation has to be taken with
a grain of salt. Some of the code might actually be in other methods, in lengthyWork in
our case, which are then called from inside run .
Search WWH ::




Custom Search