Java Reference
In-Depth Information
36
try
{
37
while
(
true
) {
38 System.out.println(
"\t\t\tConsumer reads "
+ buffer.read());
39
// Put the thread into sleep
40 Thread.sleep((
int
)(Math.random() *
10000
));
41 }
42 }
43
catch
(InterruptedException ex) {
44 ex.printStackTrace();
45 }
46 }
47 }
48
49
// An inner class for buffer
50
private static class
Buffer {
51
private static final int
CAPACITY =
1
;
// buffer size
52
private
java.util.LinkedList<Integer> queue =
53
new
java.util.LinkedList<>();
54
55
// Create a new lock
56
private static
Lock lock =
new
ReentrantLock();
create a lock
57
58
// Create two conditions
59
private static
Condition notEmpty = lock.newCondition();
create a condition
create a condition
60
private static
Condition notFull = lock.newCondition();
61
62
public void
write(
int
value) {
63 lock.lock();
// Acquire the lock
64
try
{
65
while
(queue.size() == CAPACITY) {
66 System.out.println(
"Wait for notFull condition"
);
67
acquire the lock
notFull.await();
wait for
notFull
68 }
69
70 queue.offer(value);
71
notEmpty.signal();
// Signal notEmpty condition
signal
notEmpty
72 }
73
catch
(InterruptedException ex) {
74 ex.printStackTrace();
75 }
76
finally
{
77
lock.unlock();
// Release the lock
release the lock
78 }
79 }
80
81
public int
read() {
82
int
value =
0
;
83 lock.lock();
// Acquire the lock
84
try
{
85
while
(queue.isEmpty()) {
86 System.out.println(
"\t\t\tWait for notEmpty condition"
);
87
acquire the lock
notEmpty.await();
wait for
notEmpty
88 }
89
90 value = queue.remove();
91
notFull.signal();
// Signal notFull condition
signal
notFull
92 }
93
catch
(InterruptedException ex) {
94 ex.printStackTrace();
95 }
Search WWH ::
Custom Search