Java Reference
In-Depth Information
36 synchronized (collectionPlate) {
37 int amount = collectionPlate.amount + contribution;
38 String msg = "Contributing: current amount: " + amount;
39 System.out.println(msg);
40 collectionPlate.amount = amount;
41 collectionPlate.notify();
42 }
43 }
44 }
45
46 /**
47 * Thread that checks the collections made.
48 */
49 private class CollectionChecker extends Thread {
50 public void run() {
51 // check the amount of money in the collection plate. If it's
52 // less than 100, then release the collection plate, so other
53 // Threads can modify it.
54 synchronized (collectionPlate) {
55 while (collectionPlate.amount < 100) {
56 try {
57 System.out.println("Waiting ");
58 collectionPlate.wait();
59 } catch (InterruptedException ie) {
60 ie.printStackTrace();
61 }
62 }
63 // getting past the while statement means that the
64 // contribution goal has been met.
65 System.out.println("Thank you");
66 }
67 }
68 }
69 }
In this case, there is one thread representing the minister waiting for the collection to exceed
$100. There are a further six threads representing attendees adding $20 to the collection plate.
Each of these threads synchronizes on the collectionPlate object. Since the threads adding to
the collection plate need to obtain the lock on the collectionPlate object, the minister thread
must temporarily release it from time to time, which it does by calling the wait method. As each
thread adds to the collection plate, it wakes the minister by calling the notify method.
Note In Listing 4-1, it does not really matter whether the collection threads call notify or notifyAll in
line 41—either call will wake the minister thread. Since there is only one thread waiting on the condition
(the amount in the collection plate) to change, we have chosen to call notify . If multiple threads were wait-
ing on different conditions to change, then it would make more sense to call notifyAll .
Search WWH ::




Custom Search