// Wait for child threads to terminate.
try {
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
System.out.println("Low-priority thread: " +;
System.out.println("High-priority thread: " +;
The output of this program, shown as follows when run under Windows, indicates that
the threads did context switch, even though neither voluntarily yielded the CPU nor blocked
for I/O. The higher-priority thread got the majority of the CPU time.
Low-priority thread: 4408112
High-priority thread: 589626904
Of course, the exact output produced by this program depends on the speed of your CPU
and the number of other tasks running in the system. When this same program is run under
a nonpreemptive system, different results will be obtained.
One other note about the preceding program. Notice that running is preceded by the
keyword volatile. Although volatile is examined more carefully in Chapter 13, it is used
here to ensure that the value of running is examined each time the following loop iterates:
while (running) {
Without the use of volatile, Java is free to optimize the loop in such a way that a local copy
of running is created. The use of volatile prevents this optimization, telling Java that running
may change in ways not directly apparent in the immediate code.
When two or more threads need access to a shared resource, they need some way to ensure
that the resource will be used by only one thread at a time. The process by which this is
achieved is called synchronization. As you will see, Java provides unique, language-level
support for it.
Key to synchronization is the concept of the monitor (also called a semaphore). A monitor
is an object that is used as a mutually exclusive lock, or mutex. Only one thread can own a
monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor.
All other threads attempting to enter the locked monitor will be suspended until the first
thread exits the monitor. These other threads are said to be waiting for the monitor. A thread
that owns a monitor can reenter the same monitor if it so desires.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks