wait()并notify()协同工作-当一个线程调用wait()一个对象时,该线程将阻塞,直到另一个线程调用notify()或notifyAll()对该对象调用。
(另请参见:wait()/ notify())
package com.example.examples.object;
import java.util.concurrent.atomic.AtomicBoolean;
public class WaitAndNotify {
public static void main(String[] args) throws InterruptedException {
final Object obj = new Object();
AtomicBoolean aHasFinishedWaiting = new AtomicBoolean(false);
Thread threadA = new Thread("Thread A") {
public void run() {
System.out.println("A1: Could print before or after B1");
System.out.println("A2: Thread A is about to start waiting...");
try {
synchronized (obj) { // wait()必须在同步块中
// 线程A的执行停止,直到调用obj.notify()
obj.wait();
}
System.out.println("A3: Thread A has finished waiting. "
+ "Guaranteed to happen after B3");
} catch (InterruptedException e) {
System.out.println("Thread A was interrupted while waiting");
} finally {
aHasFinishedWaiting.set(true);
}
}
};
Thread threadB = new Thread("Thread B") {
public void run() {
System.out.println("B1: Could print before or after A1");
System.out.println("B2: Thread B is about to wait for 10 seconds");
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000); // 睡一秒钟
} catch (InterruptedException e) {
System.err.println("Thread B was interrupted from waiting");
}
}
System.out.println("B3: Will ALWAYS print before A3 since "
+ "A3 can only happen after obj.notify() is called.");
while (!aHasFinishedWaiting.get()) {
synchronized (obj) {
// 通知一个已调用obj.wait()的线程
obj.notify();
}
}
}
};
threadA.start();
threadB.start();
threadA.join();
threadB.join();
System.out.println("Finished!");
}
}一些示例输出:
A1: Could print before or after B1 B1: Could print before or after A1 A2: Thread A is about to start waiting... B2: Thread B is about to wait for 10 seconds B3: Will ALWAYS print before A3 since A3 can only happen after obj.notify() is called. A3: Thread A has finished waiting. Guaranteed to happen after B3 Finished! B1: Could print before or after A1 B2: Thread B is about to wait for 10 seconds A1: Could print before or after B1 A2: Thread A is about to start waiting... B3: Will ALWAYS print before A3 since A3 can only happen after obj.notify() is called. A3: Thread A has finished waiting. Guaranteed to happen after B3 Finished! A1: Could print before or after B1 A2: Thread A is about to start waiting... B1: Could print before or after A1 B2: Thread B is about to wait for 10 seconds B3: Will ALWAYS print before A3 since A3 can only happen after obj.notify() is called. A3: Thread A has finished waiting. Guaranteed to happen after B3 Finished!