Java Reference
In-Depth Information
30.19
✓
✓
How do you create a condition on a lock? What are the
await()
,
signal()
, and
signalAll()
methods for?
Check
Point
30.20
What would happen if the
while
loop in line 58 of Listing 30.6 was changed to an
if
statement?
Replaced by
while
(balance < amount)
if
(balance < amount)
30.21
Why does the following class have a syntax error?
public class
Test
implements
Runnable {
public static void
main(String[] args) {
new
Test();
}
public
Test()
throws
InterruptedException {
Thread thread =
new
Thread(
this
);
thread.sleep(
1000
);
}
public synchronized void
run() {
}
}
30.22
What is a possible cause for
IllegalMonitorStateException
?
30.23
Can the
wait()
,
notify()
, and
notifyAll()
be invoked from any object? What
is the purpose of these methods?
30.24
What is wrong in the following code?
synchronized
(object1) {
try
{
while
(!condition) object2.wait();
}
catch
(InterruptedException ex) {
}
}
This section gives the classic Consumer/Producer example for demonstrating thread
coordination.
Key
Point
Suppose you use a buffer to store integers and that the buffer size is limited. The buffer pro-
vides the method
write(int)
to add an
int
value to the buffer and the method
read()
to read and delete an
int
value from the buffer. To synchronize the operations, use a lock
with two conditions:
notEmpty
(i.e., the buffer is not empty) and
notFull
(i.e., the buffer
is not full). When a task adds an
int
to the buffer, if the buffer is full, the task will wait for
the
notFull
condition. When a task reads an
int
from the buffer, if the buffer is empty, the
task will wait for the
notEmpty
condition. The interaction between the two tasks is shown in
Figure 30.18.
Listing 30.7 presents the complete program. The program contains the
Buffer
class (lines
50-101) and two tasks for repeatedly adding and consuming numbers to and from the buffer
(lines 16-47). The
write(int)
method (lines 62-79) adds an integer to the buffer. The
read()
method (lines 81-100) deletes and returns an integer from the buffer.
Search WWH ::
Custom Search