In this simple example I have two synchronized (theLock) that are accessed by different threads
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");
}
}
Why the newly created thread can access to synchronized (theLock) section inside? As far as I understand, theLock is already acquired by the main thread and the new one should block forever. Instead I see that it enters to synchronized as well.
Here is an output
start
main thread id : 1
new thread id : 13. Inside thread
inside synchronized
end
The call to
wait()releases the lock. Perwait()Javadoc (bolding mine):