Java Reference
In-Depth Information
84.
public void run(){
85.
System.out.println("WorkerThread"+num+": started as "+
86.
Thread.currentThread().getName());
87.
lengthyWork();
88.
System.out.println("WorkerThread"+num+": Done");
89.
}
90.
91.
}
92.
93. }
20.3
Side-effects
!
There are some side-effects to be aware of:
As the GUI is not blocked after selecting the menu item 'Start', we can immedi-
ately select it again, and again. . . . Every time a new WorkerThread is created
and started all these threads run in parallel. What happens can best be seen
in the console's output. If this is unwanted, one has to check whether there
already is a worker thread running before starting the next one. This can be
done by setting a 'flag' (e.g. a boolean variable) before starting the thread and
have the thread reset it just before it exits (last command in the run method).
There are other ways of achieving this which require a deeper knowledge of
threads.
Sometimes the blocking of the GUI is not that unwanted. If, for example, a large
file is read, then one might not want further user commands to be processed
before the whole file has been loaded. Here, so-called progress meters might
be a more elegant way of solving the problem.
If, in our example, a number of threads for the lengthy work are started, all of
them are slowed down. They do not finish after five seconds each. The reason
is that on one-processor systems - and most computers just have one main
processor - the different threads do not really run concurrently. Instead, they
have to share the single processor. Each one runs only for a short time and is
then interrupted while another thread continues to run for a short time, etc.
The different threads receive time slices .
20.4
Updating a display at runtime
20.4.1
The problem
Consider the situation where a complex drawing is displayed and has to be peri-
odically updated. This is a typical setting when data are continuously received,
Search WWH ::




Custom Search