3. wait, notify, notifyAll
class Shared {
private boolean available = false;
public synchronized void produce() throws InterruptedException {
while (available) {
wait();
}
available = true;
notify();
}
public synchronized void consume() throws InterruptedException {
while (!available) {
wait();
}
available = false;
notify();
}
}wait lets the thread produce for some unknown amount of time (unreliable, therefore while!). We use notify to wake up one waiting thread and notifyAll to wake up all.
Why only in synchronized blocks?
Integers are updated by copy and reassigning! AtomicIntegers are updated by reference!
Watch out with String: Java uses String pools, so two unrelated strings might reference the same object. If you lock one, you might accidentally lock the other.