Java Reference
In-Depth Information
The code to draw the picture generally runs under the control of a timer so that it executes at a fixed
rate, for example, 20 times per second. Of course, nothing else can happen in the same thread while the
loop is running. If you want to have another animation running, it must be in a separate thread. Then
the multitasking capability of your operating system can allow the two threads to share the available
processor time, thus allowing both animations to run.
Let's get an idea of the principles behind how threads operate. Consider a very simple program that
consists of three activities:
Reads a number of blocks of data from a file
Performs some calculation on each block of data
Writes the results of the calculation to another file
You could organize the program as a single sequence of activities. In this case the activities- read file,
process, write file- run in sequence, and the sequence is repeated for each block to be read and
processed. You could also organize the program so that reading a block from the file is one activity,
performing the calculation is a second activity, and writing the results is a third activity. Both of these
situations are illustrated below.
Single Thread
thread 1
read block 1
calculate 1
write 1
read block 2
calculate 2
write 2
Multiple Threads
read block 1
calculate 1
write 1
read block 2
calculate 2
write 2
read block 3
calculate 3
write 3
Time
thread 1
thread 2
thread 3
Once a block of data has been read, the computation process can start, and as soon as the computation
has been completed, the results can be written out. With the program executing each step in sequence
(that is, as a single thread), as shown in the top half of the diagram, the total time for execution will be
the sum of the times for each of the individual activities. However, suppose we were able to execute
each of the activities independently, as illustrated in the lower half of the diagram. In this case, reading
the second block of data can start as soon as the first block has been read, and in theory we can have all
three activities executing concurrently. This is possible even though you only have one processor,
because the input and output operations are likely to require relatively little processor time while they
are executing, so the processor can be doing other things while they are in progress. This can have the
effect of reducing the total execution time for the program.
Search WWH ::




Custom Search