在Java中,wait()方法用于让当前线程等待,直到其他线程调用同一个对象的notify()或notifyAll()方法。当线程被唤醒后,它需要重新获取对象的锁,然后才能继续执行。
以下是一个简单的示例,说明如何使用wait()和notify()方法唤醒线程:
public class WaitNotifyExample {
private static final Object lock = new Object();
private static boolean condition = false;
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 1: Waiting for condition...");
try {
lock.wait(); // 当前线程等待
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1: Condition met, continuing execution...");
}
});
Thread thread2 = new Thread(() -> {
synchronized (lock) {
try {
Thread.sleep(2000); // 让线程1等待一段时间
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2: Setting condition to true...");
condition = true;
lock.notify(); // 唤醒线程1
}
});
thread1.start();
thread2.start();
}
}
在这个示例中,我们有两个线程:thread1和thread2。thread1首先进入wait()方法等待条件满足。thread2在等待一段时间后,将条件设置为true,然后调用notify()方法唤醒thread1。thread1被唤醒后,重新获取锁并继续执行。