Java Reference
In-Depth Information
public static void startBalanceMonitorThread() {
// Start a thread that monitors the balance value
Thread t = new Thread(() -> {
while (true) {
monitorBalance();
}
});
t.start();
}
}
I will show examples of using the
wait()
and
notify()
methods in the next section, which discusses the
producer/consumer problem.
The
wait()
method in the
java.lang.Object
class is overloaded and it has three versions:
•
wait()
: The thread waits in the object's wait set until another thread calls the
notify()
or
notifyAll()
method on the same object.
•
wait(long timeinMillis)
: The thread waits in the object's wait set until another thread
calls the
notify()
or
notifyAll()
method on the same object or the specified amount of
timeinMillis
time has elapsed.
•
wait(long timeinMillis, long timeinNanos)
: This version lets you specify time in
milliseconds and nanoseconds.
The Producer/Consumer Synchronization Problem
The producer/consumer is a typical thread synchronization problem that uses the
wait()
and
notify()
methods.
I will keep it simple. The problem statement goes like this:
There are four classes:
Buffer
,
Producer
,
Consumer
, and
ProducerConsumerTest
. An object of the Buffer
class will have an integer data element that will be produced by the producer and consumed by
the consumer. Therefore, in this example, a
Buffer
object can hold only one integer at a point in
time. Your goal is to synchronize the access to the buffer, so the Producer produces a new data
element only when the Buffer is empty and the Consumer consumes the buffer's data only when it is
available. The
ProducerConsumerTest
class is used to test the program.
Listing 6-6, Listing 6-7, Listing 6-8, and Listing 6-9 contain the code for the four classes.
Listing 6-6.
A Buffer Class for Producer/Consumer Synchronization
// Buffer.java
package com.jdojo.threads;
public class Buffer {
private int data;
private boolean empty;
public Buffer() {
this.empty = true;
}