Java Reference
In-Depth Information
int
int
Task for adding an
Task for deleting an
while
(count == CAPACITY)
notFull.await();
while
(count ==
0
)
notEmpty.await();
int
int
Delete an
from the buffer
Add an
to the buffer
notEmpty.signal();
notFull.signal();
F
IGURE
30.18
The conditions
notFull
and
notEmpty
are used to coordinate task
interactions.
The buffer is actually a first-in, first-out queue (lines 52-53). The conditions
notEmpty
and
notFull
on the lock are created in lines 59-60. The conditions are bound to a lock. A
lock must be acquired before a condition can be applied. If you use the
wait()
and
notify()
methods to rewrite this example, you have to designate two objects as monitors.
L
ISTING
30.7
ConsumerProducer.java
1
import
java.util.concurrent.*;
2
import
java.util.concurrent.locks.*;
3
4
public class
ConsumerProducer {
5
private static
Buffer buffer =
new
Buffer();
create a buffer
6
7
public static void
main(String[] args) {
8
// Create a thread pool with two threads
9 ExecutorService executor = Executors.newFixedThreadPool(
2
);
10 executor.execute(
new
ProducerTask());
11 executor.execute(
new
ConsumerTask());
12 executor.shutdown();
13 }
14
15
// A task for adding an int to the buffer
16
private static class
ProducerTask
implements
Runnable {
17
public void
run() {
18
try
{
19
int
i =
1
;
20
while
(
true
) {
21 System.out.println(
"Producer writes "
+ i);
22 buffer.write(i++);
// Add a value to the buffer
23
// Put the thread into sleep
24 Thread.sleep((
int
)(Math.random() *
10000
));
25 }
26 }
27
catch
(InterruptedException ex) {
28 ex.printStackTrace();
29 }
30 }
31 }
32
33
create two threads
producer task
// A task for reading and deleting an int from the buffer
34
private static class
ConsumerTask
implements
Runnable {
consumer task
35
public void
run() {
Search WWH ::
Custom Search