Synchronized Java seems ignored

I have the following code, which I expected came to a standstill after listing "Main: pre-sync". But it seems that synchronized not doing what I expect. What's going on here?

 import java.util.*; public class deadtest { public static class waiter implements Runnable { Object obj; public waiter(Object obj) { this.obj = obj; } public void run() { System.err.println("Thead: pre-sync"); synchronized(obj) { System.err.println("Thead: pre-wait"); try { obj.wait(); } catch (Exception e) { } System.err.println("Thead: post-wait"); } System.err.println("Thead: post-sync"); } } public static void main(String args[]) { Object obj = new Object(); System.err.println("Main: pre-spawn"); Thread waiterThread = new Thread(new waiter(obj)); waiterThread.start(); try { Thread.sleep(1000); } catch (Exception e) { } System.err.println("Main: pre-sync"); synchronized(obj) { System.err.println("Main: pre-notify"); obj.notify(); System.err.println("Main: post-notify"); } System.err.println("Main: post-sync"); try { waiterThread.join(); } catch (Exception e) { } } } 

Since both threads are synchronized with the created object, I expected the threads to actually block each other. Currently, the code happily notifies of another thread, joins and exits.

+4
source share
2 answers

Calling .wait() on the monitor actually releases the synchronized lock, so another thread can block on one monitor and send a notification.

Your behavior is completely normal: the "waiter" is blocked on the monitor, and then releases the lock when waiting for a notification. After 1 second, the main thread blocks the monitor, sends a notification, unlocks the monitor, which wakes the waiter to complete its work.

+4
source

When you wait() on an object, the thread releases the object lock so that others can use the lock and notify() waiting thread. See javadoc for Object.wait() .

The current thread must own this object. The thread frees the owner of this monitor and waits until another thread notifies the threads waiting on this object monitor to wake up either through a call to the notification method or the notifyAll method. The thread then waits until it can re-acquire ownership of the monitor and resume execution .

+4
source

Source: https://habr.com/ru/post/1304866/


All Articles