Two threads executing two `synchronized` methods?

时光毁灭记忆、已成空白 提交于 2019-12-06 15:25:09

问题


I was reading about JAVA synchronization.

I have 2 methods in my class.

public synchronized void eat()
{
    System.out.println("eat");
    eatDinner();
}

public synchronized void eatDinner()
{
    System.out.println("eat");
}

Both of my methods are synchronized.

Now Is it possible for 2 threads one is calling eat() and another eatDinner() to run simultaneously? And If thread2 has not still executing eatDinner() . Can thread1 can call eatDinner() from eat()?


回答1:


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.




回答2:


"Now Is it possible for 2 threads one is calling eat() and another eatDinner() to run simultaneously? "

on the same instance, no. they will block and only one will execute at once. different class instances, yes, they will not block eath other.

"Can thread1 can call eatDinner() from eat()"

yes. the lock is reentrant.




回答3:


If 2 threads call methods on different class instances they can run methods simultaneously



来源:https://stackoverflow.com/questions/22433466/two-threads-executing-two-synchronized-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!