Java Reference
In-Depth Information
System.out.println(“Starting the hello thread...”);
thread1.start();
System.out.println(“Creating the goodbye thread...”);
DisplayMessage bye = new DisplayMessage(“Goodbye”);
Thread thread2 = new Thread(bye);
System.out.println(“Starting the goodbye thread...”);
thread2.start();
}
}
I want to make a few comments about the RunnableDemo program:
Two Runnable objects are instantiated: hello and bye.
■■
Each of the two Runnable objects is associated with a Thread object:
thread1 and thread2.
■■
Invoking start() on the Thread objects causes the thread to become
runnable.
■■
When the thread gets scheduled, the run() method on the correspond-
ing Runnable object is invoked.
■■
Just after thread2 is started, there are three threads in this process: the
main() thread, thread1, and thread2.
■■
The program does not terminate, even though main() runs to completion.
Once main() is done executing, the process still has two non-daemon
threads: thread1 and thread2. The process does not terminate until both
of these threads finish executing.
■■
That being said, this process never terminates because the two threads
do not stop (their corresponding run() methods contain infinite loops).
To stop this process, you need to stop the JVM process. (In Windows,
press Ctrl+c at the command prompt.)
■■
Figure 15.1 shows a sample output of running the RunnableDemo program.
The output was created by running the program on Windows XP, which uses
time-slicing. Notice that Hello is printed for a while; Goodbye is then printed
for a while; then the program goes back to Hello again, and so on. Running this
program probably produces a different output each time, depending on the
platform and how many other threads are running.
Search WWH ::




Custom Search