Java Reference
In-Depth Information
executed under the control of a single program — your browser — and threads make it possible for multiple
applets to be executing concurrently. In this case the threads serve to segment the activities running under
the control of the browser so that they appear to run concurrently. If you have only one processor, this is an
illusion created by your operating system because only one thread can actually be executing instructions at
any given instant, but it's a very effective illusion. To produce animation, you typically put some code that
draws a succession of still pictures in a loop that runs indefinitely. 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 both 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 simple program that consists
of three activities:
• Reading a number of blocks of data from a file
• Performing some calculation on each block of data
• Writing 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 cal-
culation is a second activity, and writing the results is a third activity. Both of these situations are illustrated
in Figure 16-1 .
FIGURE 16-1
After 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 Figure 16-1 , the total time for execution is the sum of the
times for each of the individual activities. However, suppose you were able to execute each of the activities
independently, as illustrated in the lower half of Figure 16-1 . In this case, reading the second block of data
can start as soon as the first block has been read, and in theory you can have all three activities executing
concurrently. This is possible even though you have only one processor because the input and output oper-
ations 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 reduce the total execution time for the program.
 
 
Search WWH ::




Custom Search