Achieve strong performance with threads, Part 3
Learn about thread scheduling, the wait/notify mechanism, and thread interruption
By Jeff Friesen, JavaWorld.com, 07/05/02
- Digg
- Reddit
- SlashDot
- Stumble
- del.icio.us
- Technorati
- dzone
This month, I continue my four-part thread series 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.
Read the whole series on thread programming:
Thread scheduling
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:
- Java does not force a VM to schedule threads in a specific manner or contain a thread scheduler. That implies platform-dependent
thread scheduling. Therefore, you must exercise care when writing a Java program whose behavior depends on how threads are
scheduled and must operate consistently across different platforms.
- Fortunately, when writing Java programs, you need to think about how Java schedules threads only when at least one of your
program's threads heavily uses the processor for long time periods and intermediate results of that thread's execution prove
important. For example, an applet contains a thread that dynamically creates an image. Periodically, you want the painting
thread to draw that image's current contents so the user can see how the image progresses. To ensure that the calculation
thread does not monopolize the processor, consider thread scheduling.
Examine a program that creates two processor-intensive threads:
Listing 1: SchedDemo.java
// 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:
- Digg
- Reddit
- SlashDot
- Stumble
- del.icio.us
- Technorati
- dzone
Resources
- For a glossary specific to this article, homework, and more, see the Java 101 study guide that accompanies this article
http://www.javaworld.com/javaworld/jw-07-2002/jw-0703-java101guide.html
- For a discussion of threads, see the The Java Language Specification, Second Edition, James Gosling, Bill Joy, Guy Steele, Gilad Bracha (Sun Microsystems, 2000)
http://www.javasoft.com/docs/books/jls/second_edition/html/j.title.doc.html
- The Java Tutorial, Mary Campione, Kathy Walrath, Alison Huml (Addison-Wesley, 2000; ISBN0201703939) provides a lesson on threads
http://java.sun.com/docs/books/tutorial/essential/threads/index.html
- Learn how to choose a specific thread wake-up order by reading "Apply the Specific Notification Pattern to Control the Order
of Thread Execution," Peter Haggar (IBM developerWorks, December 2001)
http://www-106.ibm.com/developerworks/java/library/j-spnotif/?dwzone=java
- Learn how to handle InterruptedException objects by reading this TechTip"Handling Those Pesky InterruptedExceptions," Stuart
Halloway (Java Developer Connection, April 2000)
http://developer.java.sun.com/developer/TechTips/2000/tt0425.html#tip2
- Allen Holub gives a real-world perspective to programming Java threads in his JavaWorld series "Programming Java Threads in the Real World:"
- Part 1A Java programmer's guide to threading architectures (September 1998)
- Part 2The perils of race conditions, deadlock, and other threading problems (October 1998)
- Part 3Roll-your-own mutexes and centralized lock management (November 1998)
- Part 4Condition variables and counting semaphores—filling in a few chinks in Java's threading model (December 1998)
- Part 5Has Sun abandoned run anywhere? PlusThreads and Swing, timers, and getting around stop(), suspend(), and resume() deprecation (February 1999)
- Part 6The Observer pattern and mysteries of the AWTEventMulticaster (March 1999)
- Part 7Singletons, critical sections, and reader/writer locks (April 1999)
- Part 8Threads in an object-oriented world, thread pools, implementing socket accept loops (May 1999)
- Part 9More threads in an object-oriented worldSynchronous dispatchers, active objects, detangling console I/O (June 1999)