awaitSignal

open fun awaitSignal(condition: Condition)

Waits on monitor until it is signaled. Throws InterruptedIOException if either the thread is interrupted or if this timeout elapses before monitor is signaled. The caller must hold the lock that monitor is bound to.

Here's a sample class that uses awaitSignal() 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;

ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition();

public void roll() {
lock.withLock {
latestTotal = 2 + random.nextInt(6) + random.nextInt(6);
System.out.println("Rolled " + latestTotal);
condition.signalAll();
}
}

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

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