How to own an object monitor

I have such coding.

public class WaitTest { public static void main(String[] args) { Object object = new Object(); try { synchronized (object) { object.wait(5000); } } catch (InterruptedException e) { e.printStackTrace(); } } } 

Does the synchronized (object) use the WaitTest class, which owns the object’s monitor?

+6
source share
2 answers

Classes do not have their own monitors; threads are executed.

In your example, WaitTest does not belong to the monitor, the main thread does.

In particular, no other thread can enter a synchronized block on the same object, including calling any of the object synchronized methods if it had such methods.

+8
source

The thread belongs to the monitor, and there are three ways to own the monitor, according to the JDK white paper: Object.notify

A thread becomes the owner of an object monitor in one of three ways:

  • By executing the synchronized instance method of this object.
  • By executing the body of a synchronized statement that synchronizes with the object.
  • For objects of type Class, by executing the synchronized static method of this class.
0
source

All Articles