You need to enable JavaScript to run this app. Java线程执行wait后notify未唤醒对应线程导致后续代码不执行求助
优惠活动
大模型
产品
解决方案
定价
更多

Java线程执行wait后notify未唤醒对应线程导致后续代码不执行求助

核心问题定位
  • 两个线程分别持有独立的Achterbahn实例:t4任务逻辑中创建第一个实例,t5任务逻辑中重新创建第二个无关联的独立实例。
  • Java的wait()/notify()机制绑定在具体对象锁上:synchronized修饰的实例方法,默认锁对象为方法所属的当前实例this。t5调用wait()时,会挂在自身持有的实例对应的锁等待队列上;t4调用notify()时,仅对自身持有的另一个实例的锁发起唤醒,完全无法触达t5等待的锁队列,t5永远收不到唤醒信号。
  • 代码中定义的monitor锁对象从未被实际调用,属于冗余定义。
修复方案

调整两个线程的执行逻辑,共享同一个Achterbahn实例;同时按照Java并发规范补充等待条件判断,规避虚假唤醒问题,修改后代码:

public class Achterbahn {
    // 等待状态标志,用于规避虚假唤醒
    private boolean passengerArrived = false;

    public synchronized void test() throws InterruptedException {
        System.out.println("car");
        while (!passengerArrived) {
            wait();
        }
        System.out.println("car");
    }

    public synchronized void Passagier() throws InterruptedException {
        Thread.sleep(2000);
        System.out.println("p");
        passengerArrived = true;
        notify();
    }

    public static void main(String []args) throws InterruptedException {
        // 全局共享同一个实例,保证锁对象一致
        Achterbahn sharedInstance = new Achterbahn();
        Thread t4 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    sharedInstance.Passagier();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t5= new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    sharedInstance.test();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t4.start();
        t5.start();
        t5.join();
        t4.join();
    }
}

修改后程序运行输出:

car
p
car

内容的提问来源于stack exchange,提问作者jupyter1101

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.10 17:45:01