Synchronized
Synchronized
method and synchronized block with monitor => these are equivalent
for non-static functions that means both make threads wait when they
try to access code for same object.
If
objects are different, threads are not blocked.
So
following 2 are same:
public synchronized void foo () {
// do something
}
public void foo () {
synchronized (this) {
// do something
}
}
However,
if you add static to both the functions, then its semantic changes
and they no longer remain equivalent.
public static synchronized void foo () {
// do something
}
public static void foo () {
synchronized (this) {
// do something
}
}
Here,
first functions becomes synchronized at class level whereas second
one is still at object level. So even if the objects are different,
first function makes accessing threads wait while second function
allows for such case. If object is same, then obviously both
functions block.
|