Java Reference
In-Depth Information
How It Works
There are many ways of coordinating threads in Java, and these coordination efforts
rely on the notion of making a thread wait. When a thread waits, it suspends execution
(it doesn't continue to the next instruction and is removed from the JVM's thread
scheduler). If a thread is waiting, it can then be awakened by notifying it. Within the
Java's concurrency lingo, the word notify implies that a thread will resume execution
(the JVM will add the thread to the thread scheduler). So in the natural course of thread
coordination, the most common sequence of events is a main thread waiting, and a sec-
ondary thread then notifying the main thread to continue (or wake up). Even so, there is
the possibility of a waiting thread being interrupted by some other event. When a
thread is interrupted, it doesn't continue to the next instruction, but instead throws an
InterruptedException , which is a way of signaling that even though the thread
was waiting for something to happen, some other event happened that requires the
thread's attention. This is better illustrated by the following example:
BlockingQueue queue = new LinkedBlockingQueue();
while (true) {
synchronized (this) {
Object itemToProcess = queue.take();
processItem (itemToProcess);
}
}
If you look at the previous code, the thread that executes this code would never ter-
minate because it loops forever and waits for an item to be processed. If there are no
items in the Queue , the main thread waits until there is something added to the Queue
from another thread. You couldn't graciously shut down the previous code (especially
if the thread running the loop is not a Daemon thread).
BlockingQueue queue = new LinkedBlockingQueue();
while (true) {
synchronized (this) {
Object itemToProcess = null;
try {
itemToProcess = queue.take();
} catch (InterruptedException e) {
return;
Search WWH ::




Custom Search