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: } // 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\n%s\n", "Producer done producing.",
37: "Terminating Producer." );
38: } // end method run
39: } // end class Producer
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: *************************************************************************/