Java – how does this cause deadlocks?

I was brushing my java and was asked this question in the exercise How can the following cause deadlock?

private Object sync = new Object();

    public void methodA() throws InterruptedException {
        synchronized(this.sync) {
            Thread.sleep(1000);
        }
    }

    public void methodB() throws InterruptedException {
        synchronized(this.sync) {
            this.methodA();
        }
    }

My guess is that if methodb is executing thread When the sleep function calls methoda, will these two methods start cascading and lead to indefinite sleep?

reflection?

Solution

No, this will not cause a deadlock

To create a deadlock, you need two threads a and B and two resources X and Y. if a holds the lock on X and needs to lock y, but B holds y and needs to lock x, a deadlock will occur

You have only one thing to lock, this Sync, so no deadlock occurs

If methodb is entered when another thread calls methoda, it will wait until methoda releases the lock before continuing If you enter methoda when another thread calls methodb, wait until methodb releases the lock before continuing Note that it doesn't matter if methodb calls methoda because it's related to this Sync locks are the same

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>