public class Producer implements Runnable
1: // Fig. 23.7: Producer.java
2: // Producer's run method stores the values 1 to 10 in buffer.
3: import java.util.Random;
4:
5: public class Producer implements Runnable
6: {
7: private static Random generator = new Random();
8: private Buffer sharedLocation; // reference to shared object
9:
10: // constructor
11: public Producer( Buffer shared )
12: {
13: sharedLocation = shared;
14: } // end Producer constructor
15:
16: // store values from 1 to 10 in sharedLocation
17: public void run()
18: {
19: int sum = 0;
20:
21: for ( int count = 1; count <= 10; count++ )
22: {
23: try // sleep 0 to 3 seconds, then place value in Buffer
24: {
25: Thread.sleep( generator.nextInt( 3000 ) ); // sleep thread
26: sharedLocation.set( count ); // set value in buffer
27: sum += count; // increment sum of values
28: System.out.printf( "\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\n%s\n", "Producer done producing.",
38: "Terminating Producer." );
39: } // end method run
40: } // end class Producer
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: *************************************************************************/