Java Reference
In-Depth Information
4
import java.util.concurrent.Executors;
5
import java.util.concurrent.TimeUnit;
6
7
public class SharedBufferTest2
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 SynchronizedBuffer to store ints
15
Buffer sharedLocation = new SynchronizedBuffer();
16
17
System.out.printf( "%-40s%s\t\t%s%n%-40s%s%n%n" , "Operation" ,
18
"Buffer" , "Occupied" , "---------" , "------\t\t--------" );
19
20
// execute the Producer and Consumer tasks
21
executorService.execute( new Producer(sharedLocation));
22
executorService.execute( new Consumer(sharedLocation));
23
24
executorService.shutdown();
25
executorService.awaitTermination( 1 , TimeUnit.MINUTES );
26
}
27
} // end class SharedBufferTest2
Operation Buffer Occupied
--------- ------ --------
Producer writes 1 1 true
Producer tries to write.
Buffer full. Producer waits. 1 true
Consumer reads 1 1 false
Producer writes 2 2 true
Producer tries to write.
Buffer full. Producer waits. 2 true
Consumer reads 2 2 false
Producer writes 3 3 true
Consumer reads 3 3 false
Producer writes 4 4 true
Consumer reads 4 4 false
Consumer tries to read.
Buffer empty. Consumer waits. 4 false
Fig. 23.21 | Two threads manipulating a synchronized buffer. (Part 2 of 3.)
Search WWH ::




Custom Search