为什么通过不同的线程两次输入了“同步(锁定)”?

时间:2018-11-14 13:24:45

标签: java multithreading synchronized synchronized-block

在这个简单的示例中,我有两个synchronized (theLock),它们可以通过不同的线程进行访问

public class Main {

    public static void main(String[] args) throws InterruptedException {
        System.out.println("start");

        final Object theLock = new Object();

        synchronized (theLock) {
            System.out.println("main thread id : " + Thread.currentThread().getId());

            new Thread(() -> {
                System.out.println("new thread id : " + Thread.currentThread().getId() + ". Inside thread");

                // before entering this section new thread should be blocked as `theLock` is already acquired
                synchronized (theLock) {
                    System.out.println("inside synchronized");
                    theLock.notify();
                }
            }).start();

            theLock.wait();
        }

        System.out.println("end");
    }
}

为什么新创建的线程可以访问其中的synchronized (theLock)部分?据我了解,theLock已经被主线程获取,新线程应该永远阻塞。相反,我看到它也进入了synchronized

这是输出

start
main thread id : 1 
new thread id : 13. Inside thread
inside synchronized
end

1 个答案:

答案 0 :(得分:5)

wait()的调用释放了锁定。 Per wait() Javadoc(轰炸我):

  

使当前线程等待,直到另一个线程调用   notify()方法或此对象的notifyAll()方法。在   换句话说,此方法的行为就像它只是执行   致电wait(0)

     

当前线程必须拥有此对象的监视器。 线程   释放此监视器的所有权,并等待直到另一个线程   通知在此对象的监视器上等待的线程唤醒   通过调用notify方法或notifyAll方法。的   然后线程等待,直到它可以重新获得监视器的所有权并   恢复执行。