Java Reference
In-Depth Information
}
processItem (itemToProcess);
}
}
The new code now has the ability of “escaping” the infinite loop. From another
thread, you can call thread.interrupt() , which throws the InterruptedEx-
ception that is then caught by the main thread's catch clause. The infinite loop can
be exited within this clause.
InterruptedExceptions are a way of sending extra information to waiting
(or sleeping) threads so that they may handle a different scenario (for example, an or-
derly program shutdown). For this reason, every operation that changes the state of the
thread to sleep/wait will have to be surrounded by a try/catch block that can catch
the InterruptedException . This is one of the cases in which the exception
(InterruptedException) is not really an error but more of a way of signaling
between threads that something has occurred that requires attention.
Solution 1 demonstrates the most common (oldest) form of coordination. The solu-
tion requires making a thread wait and suspending execution until the thread gets noti-
fied (or awakened) by another thread.
For solution 1 to work, the originating thread needs to acquire a lock. This lock will
then be the “phone number” on which another thread can notify the originating thread
to wake up. After the originating thread acquires the lock (phone number), it proceeds
to wait. As soon as the wait() method is called, the lock is released, allowing other
threads to acquire the same lock. The secondary thread then proceeds to acquire the
lock (the phone number) and then notifies (which, in fact, would be like dialing a
wake-up call) the originating thread. After the notification, the originating thread re-
sumes execution.
In the solution 1 code, the lock is a dummy object identified as objectToSync.
In practice, the object on which locks are waiting and notifying could be any valid in-
stance object in Java; for example, we could have used the this reference to make the
main thread wait (and within the threads we could have used the Recipe
10_7_1.this variable reference to notify the main thread to continue).
The main advantage of using this technique is the explicitness of controlling on
whom to wait and when to notify (and the ability to notify all threads that are waiting
on the same object; see the following tip).
Search WWH ::




Custom Search