No, it is not possible for two threads to run the methods eat
and eatDinner
simultaneously. (Caveat: as long as these methods are invoked on the same instance of the class)
The synchronized
keywords, when applied to a non-static method, synchronizes on the object itself.
Your code can be rewritten, without changing the meaning, as:
public void eat() {
synchronized (this) {
System.out.println("eat");
eatDinner();
}
}
public void eatDinner() {
synchronized (this) {
System.out.println("eat");
}
}
This probably makes it easier to see that they are both synchronizing on the same monitor. Each java object has a monitor.
As long as 'thread1' is holding the monitor of your object, it can enter other synchronized
blocks on the same monitor. 'thread1' has to exit all synchronized blocks (exist the blocks as many times as it has entered them) before another thread can take ownership of the monitor.
So thread1 can call eatDinner
if it is already in the eat
method - no problem. But if thread2
is currently in the eat
method, then thread1
will block when it calls eatDinner
until thread2 has finished both eatDinner
and eat
.
Addition: In response to your comment
@Raj: If two threads are created by same class instances, then?
It is not important how the threads were created - it doesn't matter if that happened from within the same class or from completely different locations in your code. Two different threads are always independent.
It only matters on which object's monitor you synchronize: each object instance has one 'monitor'. You can't see this monitor - it doesn't have a name, but it's there and it is used by the synchronized
keywords and by the wait
, notify
and notifyAll
methods defined in java.lang.Object
.