public class Consumer implements Runnable
1: // Fig. 23.8: Consumer.java
2: // Consumer's run method loops ten times reading a value from buffer.
3: import java.util.Random;
4:
5: public class Consumer implements Runnable
6: {
7: private static Random generator = new Random();
8: private Buffer sharedLocation; // reference to shared object
9:
10: // constructor
11: public Consumer( Buffer shared )
12: {
13: sharedLocation = shared;
14: } // end Consumer constructor
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 <= 10; count++ )
22: {
23: // sleep 0 to 3 seconds, read value from buffer and add to sum
24: try
25: {
26: Thread.sleep( generator.nextInt( 3000 ) );
27: sum += sharedLocation.get();
28: } // end try
29: // if sleeping thread interrupted, print stack trace
30: catch ( InterruptedException exception )
31: {
32: exception.printStackTrace();
33: } // end catch
34: } // end for
35:
36: System.out.printf( "\n%s %d.\n%s\n",
37: "Consumer read values totaling", sum, "Terminating Consumer." );
38: } // end method run
39: } // end class Consumer
40:
41:
42: /**************************************************************************
43: * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
44: * Pearson Education, Inc. All Rights Reserved. *
45: * *
46: * DISCLAIMER: The authors and publisher of this book have used their *
47: * best efforts in preparing the book. These efforts include the *
48: * development, research, and testing of the theories and programs *
49: * to determine their effectiveness. The authors and publisher make *
50: * no warranty of any kind, expressed or implied, with regard to these *
51: * programs or to the documentation contained in these books. The authors *
52: * and publisher shall not be liable in any event for incidental or *
53: * consequential damages in connection with, or arising out of, the *
54: * furnishing, performance, or use of these programs. *
55: *************************************************************************/