Java Reference
In-Depth Information
of occupied buffer cells, the contents of the buffer cells and the current writeIndex and
readIndex . Line 51 invokes method notifyAll to allow any Producer threads waiting to
write into the CircularBuffer object to attempt to write again. Then line 53 returns the
consumed value to the caller.
CircularBuffer Method displayState
Method displayState (lines 57-86) outputs the application's state. Lines 63-64 output
the values of the buffer cells. Line 64 uses method printf with a "%2d" format specifier
to print the contents of each buffer with a leading space if it's a single digit. Lines 71-83
output the current writeIndex and readIndex with the letters W and R , respectively. Once
again, displayState is a synchronized method because it accesses class CircularBuffer 's
shared mutable data.
Testing Class CircularBuffer
Class CircularBufferTest (Fig. 23.19) contains the main method that launches the ap-
plication. Line 12 creates the ExecutorService , and line 15 creates a CircularBuffer ob-
ject and assigns its reference to CircularBuffer variable sharedLocation . Line 18
invokes the CircularBuffer 's displayState method to show the initial state of the buf-
fer. Lines 21-22 execute the Producer and Consumer tasks. Line 24 calls method shutdown
to end the application when the threads complete the Producer and Consumer tasks and
line 25 waits for the tasks to complete.
1
// Fig. 23.19: CircularBufferTest.java
2
// Producer and Consumer threads correctly manipulating a circular buffer.
3
import java.util.concurrent.ExecutorService;
4
import java.util.concurrent.Executors;
5
import java.util.concurrent.TimeUnit;
6
7
public class CircularBufferTest
8
{
9
public static void main(String[] args) throws InterruptedException
10
{
11
// create new thread pool with two threads
12
ExecutorService executorService = Executors.newCachedThreadPool();
13
14
// create CircularBuffer to store ints
CircularBuffer sharedLocation = new CircularBuffer();
15
16
17
// display the initial state of the CircularBuffer
18
sharedLocation.displayState( "Initial State" ) ;
19
20
// execute the Producer and Consumer tasks
21
executorService.execute( new Producer(sharedLocation));
executorService.execute( new Consumer(sharedLocation));
22
23
24
executorService.shutdown();
25
executorService.awaitTermination( 1 , TimeUnit.MINUTES );
26
}
27
} // end class CircularBufferTest
Fig. 23.19 | Producer and Consumer threads correctly manipulating a circular buffer. (Part 1 of 3.)
Search WWH ::




Custom Search