Vit*_*lii 0 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");
}
}
Run Code Online (Sandbox Code Playgroud)
为什么新创建的线程可以访问synchronized (theLock)里面的部分?据我所知,theLock已经被主线程获得并且新的应该永远阻止.相反,我看到它也进入了synchronized.
这是一个输出
start
main thread id : 1
new thread id : 13. Inside thread
inside synchronized
end
Run Code Online (Sandbox Code Playgroud)
wait()释放锁定的调用.Per wait()Javadoc(bolding mine):
导致当前线程等待,直到另一个线程调用此对象的
notify()方法或notifyAll()方法.换句话说,此方法的行为就像它只是执行调用一样wait(0).当前线程必须拥有此对象的监视器.线程释放此监视器的所有权并等待,直到另一个线程通过调用
notify方法或notifyAll方法通知等待此对象的监视器上的线程唤醒.然后线程等待,直到它可以重新获得监视器的所有权并继续执行.