Wait NotifyAll Guarded Block
Coordinate threads on one monitor with wait and notifyAll inside a synchronized guarded block that rechecks its condition in a while loop.
Code
public class BroadcastGate {
private static boolean ready = false;
public static synchronized void setReady() {
ready = true;
notifyAll(); // 广播唤醒所有在这个监视器上等待的线程
}
public static synchronized void awaitReady() throws InterruptedException {
// guarded block:条件判断放 while 里循环重检,虚假唤醒也能挡住
while (!ready) {
wait();
}
}
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
try {
awaitReady();
System.out.println("worker: gate open");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
worker.start();
Thread.sleep(50); // 让 worker 先进入 wait,再开门
setReady();
worker.join();
System.out.println("main: done");
}
}How it works
Count the class BroadcastGate and the function setReady as the entire surface area of Wait NotifyAll Guarded Block.
Iteration happens inside while (!ready) — everything outside it runs once.
Putting it to use
Signature: public static synchronized void setReady()
The demo output is labeled (worker: gate open, main: done), so every printed line maps back to its originating operation.
main calls 1 helper in sequence: setReady.
Core lines
public static synchronized void awaitReady() throws InterruptedException {
// guarded block:条件判断放 while 里循环重检,虚假唤醒也能挡住
while (!ready) {
wait();
}
}
public static synchronized void setReady() {
ready = true;
notifyAll(); // 广播唤醒所有在这个监视器上等待的线程
}
Thread.sleep(50); // 让 worker 先进入 wait,再开门
setReady();
Interactive Tools for This Topic
FAQ
- What does Wait NotifyAll Guarded Block print when run?
- Running the file directly is enough — expect labeled output lines such as `worker: gate open`, `main: done`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.