public class Consumer extends Thread
1: //Consumer.java
2: // Consumer's run method controls a thread that loops four
3: // times and reads a value from sharedLocation each time.
4:
5: public class Consumer extends Thread
6: {
7: private Buffer sharedLocation; // reference to shared object
8:
9: // constructor
10: public Consumer( Buffer shared )
11: {
12: super( "Consumer" );
13: sharedLocation = shared;
14: }
15:
16: // read sharedLocation's value four times and sum the values
17: public void run()
18: {
19: int sum = 0;
20:
21: for ( int count = 1; count <= 4; count++ )
22: {
23: // sleep 0 to 3 seconds, read value from Buffer and add to sum
24: try
25: {
26: Thread.sleep( ( int ) ( Math.random() * 3001 ) );
27: sum += sharedLocation.get();
28: }
29:
30: // if sleeping thread interrupted, print stack trace
31: catch ( InterruptedException exception )
32: {
33: exception.printStackTrace();
34: }
35: }
36:
37: System.err.println( getName() + " read values totaling: " + sum +
38: ".\nTerminating " + getName() + ".");
39:
40: } // end method run
41:
42: } // end class Consumer
43: