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: System.out.printf( "\t\t\t%2d\n", sum );
29: } // end try
30: // if sleeping thread interrupted, print stack trace
31: catch ( InterruptedException exception )
32: {
33: exception.printStackTrace();
34: } // end catch
35: } // end for
36:
37: System.out.printf( "\n%s %d.\n%s\n",
38: "Consumer read values totaling", sum, "Terminating Consumer." );
39: } // end method run
40: } // end class Consumer
41:
42:
43: /**************************************************************************
44: * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
45: * Pearson Education, Inc. All Rights Reserved. *
46: * *
47: * DISCLAIMER: The authors and publisher of this book have used their *
48: * best efforts in preparing the book. These efforts include the *
49: * development, research, and testing of the theories and programs *
50: * to determine their effectiveness. The authors and publisher make *
51: * no warranty of any kind, expressed or implied, with regard to these *
52: * programs or to the documentation contained in these books. The authors *
53: * and publisher shall not be liable in any event for incidental or *
54: * consequential damages in connection with, or arising out of, the *
55: * furnishing, performance, or use of these programs. *
56: *************************************************************************/