Java Reference
In-Depth Information
The Output of a Multithreaded Program
Now is a good time to point out that you cannot exactly determine the output of a
multithreaded program because you do not control when the threads get to execute. The
actual output of the CountToTen program is indeterminate because it can change every
time the program is executed.
Given that, I ran CountToTen many times and each result was the same as the previous
one. The most likely reason that the output was similar each time is that the program's
threads do not perform a lot of computations. The code is executed so quickly that the
main thread ends before the new thread has a chance to run. To test this hypothesis, I
modifi ed the for loops in both SayHello and CountToTen so that they executed 50 times
instead of 10 times, and here is a sample output of that result:
123456789101112HiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHi
HiHiHiHiHiHiHi131415161718192021222324252627282930313233343536373839
4041424344454647HiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiEnd of run
484950End of main
Notice how this time the two threads took turns on the CPU. The main thread printed the
numbers 1 to 12 , and then gave up the CPU while the SayHello thread printed “Hi” . The
output varies on different executions of the program, and you might see entirely different
results running this code on different platforms and environments.
Let's look at another example of writing a thread, except this time I demonstrate
extending the Thread class instead of implementing Runnable .
Extending the Thread Class
You can create a thread by writing a class that extends the Thread class and overriding the
run method. (A class that extends Thread is still a Runnable object because the Thread class
implements Runnable .) The following class demonstrates this technique:
1. public class MyThread extends Thread {
2. private String message;
3. private boolean keepGoing;
4.
5. public MyThread(String m) {
6. message = m;
7. keepGoing = true;
8. }
Search WWH ::




Custom Search