在java中,synchronized关键字用于获取对象监视器锁,而wait()方法必须在同步代码块内调用以释放当前持有的锁并让出cpu。具体做法是:在synchronized块中调用object.wait(),线程会进入等待状态并释放锁,其他线程可通过notify()或notifyall()唤醒它。

synchronized块中调用wait()的正确结构是什么
正确结构是将wait()放在synchronized块内部,确保线程持有锁时才执行等待。这样能避免IllegalMonitorStateException异常,并保证锁的原子性释放。

public class WaitExample { private Object lock = new Object(); public void producer() { synchronized (lock) { System.out.println("Producer waiting..."); try { lock.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } System.out.println("Producer resumed."); } } public static void main(String[] args) { WaitExample ex = new WaitExample(); new Thread(ex::producer).start(); }}运行上述代码,输出为:
Producer waiting...
(程序挂起,直到被唤醒)
立即学习“Java免费学习笔记(深入)”;
如何从另一个线程唤醒等待中的线程
通过调用同一对象的notify()或notifyAll()来唤醒等待线程。必须确保唤醒操作也在synchronized块内,且针对同一锁对象。

public class NotifyExample { private Object lock = new Object(); public void waiter() { synchronized (lock) { try { lock.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } System.out.println("Waiter notified."); } } public void notifier() { synchronized (lock) { lock.notify(); System.out.println("Notifier called notify."); } } public static void main(String[] args) throws InterruptedException { NotifyExample ex = new NotifyExample(); new Thread(ex::waiter).start(); Thread.sleep(100); ex.notifier(); }}运行结果:
Notifier called notify.
Waiter notified.
如果wait()不在synchronized块中会抛出什么异常
会抛出java.lang.IllegalMonitorStateException,因为wait()要求当前线程持有对象的监视器锁。这是Java内存模型对同步原语的基本约束,防止非原子操作导致的数据竞争。


















