Java Reference
In-Depth Information
Example 4−1: ThreadDemo.java (continued)
// We could wait for the threads to stop running with these lines
// But they aren't necessary here, so we don't bother.
// try {
// thread1.join();
// thread2.join();
// } catch (InterruptedException e) {}
// The Java VM exits only when the main() method returns, and when all
// threads stop running (except for daemon threads--see setDaemon()).
}
// ThreadLocal objects respresent a value accessed with get() and set().
// But they maintain a different value for each thread. This object keeps
// track of how many times each thread has called compute().
static ThreadLocal numcalls = new ThreadLocal();
/** This is the dummy method our threads all call */
static synchronized void compute() {
// Figure out how many times we've been called by the current thread
Integer n = (Integer) numcalls.get();
if (n == null) n = new Integer(1);
else n = new Integer(n.intValue() + 1);
numcalls.set(n);
// Display the name of the thread, and the number of times called
System.out.println(Thread.currentThread().getName() + ": " + n);
// Do a long computation, simulating a "compute-bound" thread
for(int i = 0, j=0; i < 1000000; i++) j += i;
// Alternatively, we can simulate a thread subject to network or I/O
// delays by causing it to sleep for a random amount of time:
try {
// Stop running for a random number of milliseconds
Thread.sleep((int)(Math.random()*100+1));
}
catch (InterruptedException e) {}
// Each thread politely offers the other threads a chance to run.
// This is important so that a compute-bound thread does not "starve"
// other threads of equal priority.
Thread.yield();
}
}
Threads and Thread Groups
Every Java Thread belongs to some ThreadGroup and may be constrained and con-
trolled through the methods of that ThreadGroup . Similarly, every ThreadGroup is
itself contained in some parent ThreadGroup . Thus, there is a hierarchy of thread
groups and the threads they contain. Example 4-2 shows a ThreadLister class,
with a public listAllThreads() method that displays this hierarchy by listing all
threads and thread groups currently running on the Java interpreter. This method
displays the name and priority of each thread, as well as other information about
threads and thread groups. The example defines a main() method that creates a
Search WWH ::




Custom Search