Java Reference
In-Depth Information
Calling myObject.wait for a given object myObject , however, does release that object's
lock, assuming you have the lock on that object—if you do not have the lock on that object,
attempting to call the wait method will result in an IllegalStateException being thrown. This
is actually very useful, because it allows other threads to modify myObject . This is illustrated
later in this chapter in the “Ice Cream Man” example.
To understand the wait method, think of the minister of a church passing around a col-
lection plate. He expects people to modify the collection plate's state—as a matter of fact he's
waiting for them to do so. If they don't, he'll probably continue to wait until they do. In code,
this might look something like Listing 4-1. Don't be discouraged if the code samples aren't
100 percent clear to you right now. Read the entire chapter, and it will all fall into place.
Listing 4-1. Waiting Example
1 public class Minister {
2 private CollectionPlate collectionPlate = new CollectionPlate();
3
4 public static void main(String[] args) {
5 Minister minister = new Minister();
6
7 // create a Thread that checks the amount of
8 // money in the collection plate.
9 minister.new CollectionChecker().start();
10
11 //create several threads to accept contributions.
12 for (int i = 0; i < 6; i++) {
13 minister.new CollectionAcceptor(20).start();
14 }
15 }
16
17 /**
18 * the collection plate that get passed around
19 */
20 private class CollectionPlate {
21 int amount = 0;
22 }
23
24 /**
25 * Thread that accepts collections.
26 */
27 private class CollectionAcceptor extends Thread {
28 int contribution = 0;
29
30 public CollectionAcceptor(int contribution) {
31 this.contribution = contribution;
32 }
33
34 public void run() {
35 //Add the contributed amount to the collectionPlate.
Search WWH ::




Custom Search