Java Reference
In-Depth Information
of that task's thread of execution. This fact becomes important in Sections 23.6-23.8 when
we add synchronization to the producer/consumer relationship.
1
// Fig. 23.10: Producer.java
2
// Producer with a run method that inserts the values 1 to 10 in buffer.
3
import java.security.SecureRandom;
4
5
6
public class Producer implements Runnable
{
7
private static final SecureRandom generator = new SecureRandom();
8
private final Buffer sharedLocation; // reference to shared object
9
10
// constructor
11
public Producer(Buffer sharedLocation)
12
{
13
this .sharedLocation = sharedLocation;
14
}
15
16
// store values from 1 to 10 in sharedLocation
public void run()
17
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 )); // random sleep
sharedLocation.blockingPut(count); // set value in buffer
26
27
sum += count; // increment sum of values
28
System.out.printf( "\t%2d%n" , sum);
29
}
30
catch (InterruptedException exception)
31
{
32
Thread.currentThread().interrupt();
33
}
34
}
35
36
System.out.printf(
37
"Producer done producing%nTerminating Producer%n" );
38
}
39
} // end class Producer
Fig. 23.10 | Producer with a run method that inserts the values 1 to 10 in buffer. ( Caution:
The example of Figs. 23.9-23.13 is not thread safe.)
Class Consumer
Class Consumer (Fig. 23.11) also implements interface Runnable , allowing the Consumer
to execute concurrently with the Producer . Lines 11-14 initialize Buffer reference
sharedLocation with an object that implements the Buffer interface (created in main ,
Fig. 23.13) and passed to the constructor as the parameter shared . As we'll see, this is the
same UnsynchronizedBuffer object that's used to initialize the Producer object—thus,
Search WWH ::




Custom Search