为什么调用 wait 和 notifyAll 必须是同一个对象

public static void main(String[] args) throws InterruptedException {
    TestThread t1 = new TestThread();
    t1.setName("T1");
    t1.start();

    TestThread t2 = new TestThread();
    t2.setName("T2");
    t2.start();

    final Object l =  App.class;
    synchronized (l) {
        t1.notifyAll();
        t2.notifyAll();
    }
}

static class TestThread extends Thread {
    final Object l =  App.class;
    @Override
    public void run() {
        synchronized (l) {
            try {
                System.out.println("线程名: " + this.getName() + ", wait");
                l.wait();
                System.out.println("线程名: " + this.getName() + ", 不打印");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
阅读 1.8k
1 个回答

因为那个锁,包括wait set这些东西都是属于对象的 (intrinsic lock)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题