多线程:相同的两个 object 正在进入同步块

Multithreading: Same two object is entering into synchronized block

可能是我的header不正确。

我已经开始 java 编程的多线程概念。因为我已经在同步块中阅读过,所以只有一个线程会插入特定的 object 锁。但是在查看该程序的输出后我感到困惑。 包裹 com.example.classandobjectlevellock;

class MyThread 实现 Runnable { Object ob = new Object();

public void run() {

    synchronized (this) {

        System.out.println(Thread.currentThread().getName()+" Is waitng");
        try {
            this.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

}

public class ClassAndObjectLevelLock {

public static void main(String[] args) throws InterruptedException {

    MyThread task1 =  new MyThread();
    MyThread task2 =  new MyThread();

    Thread t1 = new Thread(task1,"Thread1");
    Thread t2 = new Thread(task1,"Thread2");

    Thread t3 = new Thread(task2,"Thread3");

    t1.start();
    Thread.sleep(1000);
    t2.start();
    Thread.sleep(1000);
    t3.start();

}

} 输出: Thread1 正在等待 Thread2 正在等待 Thread3 正在等待

如果我没记错的话,线程 1 和线程 3 正在进入同步方法,因为它有两个不同的目标 object。但是为什么Thread-2进入同步块?

请帮助我理解这一点。 提前致谢。

调用wait()导致锁被释放。

根据 the wait() Javadocs:

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.