waitUntilNotified

open fun waitUntilNotified(monitor: Any)

Waits on monitor until it is notified. Throws InterruptedIOException if either the thread is interrupted or if this timeout elapses before monitor is notified. The caller must be synchronized on monitor.

Here's a sample class that uses waitUntilNotified() to await a specific state. Note that the call is made within a loop to avoid unnecessary waiting and to mitigate spurious notifications.

class Dice {
Random random = new Random();
int latestTotal;

public synchronized void roll() {
latestTotal = 2 + random.nextInt(6) + random.nextInt(6);
System.out.println("Rolled " + latestTotal);
notifyAll();
}

public void rollAtFixedRate(int period, TimeUnit timeUnit) {
Executors.newScheduledThreadPool(0).scheduleAtFixedRate(new Runnable() {
public void run() {
roll();
}
}, 0, period, timeUnit);
}

public synchronized void awaitTotal(Timeout timeout, int total)
throws InterruptedIOException {
while (latestTotal != total) {
timeout.waitUntilNotified(this);
}
}
}