object synchronization
When a synchronized block is used for synchronization on an object instance, then threads co开发者_开发百科mpete to get into object's implicit monitor. And once, any particular thread enters into the monitor, any other thread has to wait for entering into it. Then
synchronized(object){
// some code here
// no function call
}
must not enforce taking any particular type of object. Thus any object type can be used here because every object has its implicit monitor.
Kindly reply me is it true?
Yes, every Java Object can act as a monitor.
And since this is such a short answer, for bonus, this is an interesting read: Does the JVM create a mutex for every object in order to implement the 'synchronized' keyword? If not, how?
Also note that C# does something similar with their objects, but also have value types (which are not Monitors)
Just keep in mind that if you have a variable that is null
, you cannot lock it. Also, while things like Integer
are objects, an int
or float
is not. You can lock an Integer
or int[]
, but not an int
.
精彩评论