|
|
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
This month, I continue my four-part introduction to Java threads by focusing on thread scheduling, the wait/notify mechanism, and thread interruption. You'll investigate how either a JVM or an operating-system thread scheduler chooses the next thread for execution. As you'll discover, priority is important to a thread scheduler's choice. You'll examine how a thread waits until it receives notification from another thread before it continues execution and learn how to use the wait/notify mechanism for coordinating the execution of two threads in a producer-consumer relationship. Finally, you'll learn how to prematurely awaken either a sleeping or a waiting thread for thread termination or other tasks. I'll also teach you how a thread that is neither sleeping nor waiting detects an interruption request from another thread.
Note that this article (part of the JavaWorld archives) was updated with new code listings and downloadable source code in May 2013.
In an idealized world, all program threads would have their own processors on which to run. Until the time comes when computers have thousands or millions of processors, threads often must share one or more processors. Either the JVM or the underlying platform's operating system deciphers how to share the processor resource among threads—a task known as thread scheduling. That portion of the JVM or operating system that performs thread scheduling is a thread scheduler.
Note: To simplify my thread scheduling discussion, I focus on thread scheduling in the context of a single processor. You can extrapolate this discussion to multiple processors; I leave that task to you.
Remember two important points about thread scheduling:
Examine a program that creates two processor-intensive threads:
// SchedDemo.java
class SchedDemo
{
public static void main (String [] args)
{
new CalcThread ("CalcThread A").start ();
new CalcThread ("CalcThread B").start ();
}
}
class CalcThread extends Thread
{
CalcThread (String name)
{
// Pass name to Thread layer.
super (name);
}
double calcPI ()
{
boolean negative = true;
double pi = 0.0;
for (int i = 3; i < 100000; i += 2)
{
if (negative)
pi -= (1.0 / i);
else
pi += (1.0 / i);
negative = !negative;
}
pi += 1.0;
pi *= 4.0;
return pi;
}
public void run ()
{
for (int i = 0; i < 5; i++)
System.out.println (getName () + ": " + calcPI ());
}
}
SchedDemo creates two threads that each calculate the value of pi (five times) and print each result. Depending upon how your JVM implementation
schedules threads, you might see output resembling the following: