Java Reference
In-Depth Information
There is another point of interest to notice in this first threading example. To illustrate the
fact that the main thread and mt execute concurrently, it is necessary to keep main( ) from
terminating until mt is finished. Here, this is done through the timing differences between
the two threads. Because the calls to sleep( ) inside main( ) 's for loop cause a total delay
of 5 seconds (50 iterations times 100 milliseconds), but the total delay within run( ) 's loop
is only 4 seconds (10 iterations times 400 milliseconds), run( ) will finish approximately 1
second before main( ) . As a result, both the main thread and mt will execute concurrently
until mt ends. Then, about 1 second later main( ) ends.
Although this use of timing differences to ensure that main( ) finishes last is sufficient
for this simple example, it is not something that you would normally use in practice. Java
provides much better ways of waiting for a thread to end. It is, however, sufficient for the
next few programs. Later in this chapter, you will see a better way for one thread to wait
until another completes.
One other point: In a multithreaded program, you often will want the main thread to be
the last thread to finish running. As a general rule, a program continues to run until all
of its threads have ended. Thus, having the main thread finish last is not a requirement. It
is, however, often a good practice to follow—especially when you are first learning about
threads.
Some Simple Improvements
While the preceding program is perfectly valid, some simple improvements will make it
more efficient and easier to use. First, it is possible to have a thread begin execution as soon
Search WWH ::




Custom Search