educative.io

Why we are making the main thread sleep?

// sleep to make sure thread 1 gets a chance to acquire lock1
Thread.sleep(100);

What’s the use of this statement?

The increment function is only getting called by Thread1, implying that lock1 can be acquired by it only. How come the main Thread can acquire lock1?

Hi @Shubham_Sharma,

Thank you so much for reaching out to us.

Below is the code of incrementCounter() and decrementCounter() as you can see that lock1 is first acquired by incrementCounter() and required by decrementCounter() later.

void incrementCounter() throws InterruptedException {
        synchronized (lock1) {
            System.out.println("Acquired lock1");
            Thread.sleep(100);

            synchronized (lock2) {
                counter++;
            }
        }
    }

    void decrementCounter() throws InterruptedException {
        synchronized (lock2) {
            System.out.println("Acquired lock2");
            
            Thread.sleep(100);
            synchronized (lock1) {
                counter--;
            }
        }
    }

Since the lock1 is not released by incrementCounter() so it can not be acquired by decrementCounter(). The same goes for lock2 but opposite functions. Both of them cause deadlock.

I hope I have answered your question, but please feel free to ask if there is any confusion. Thank you so much.