Jeet Jain wrote:How can 4 ever print before 2? Thread t will never enter synchronized block because it does not hold lock on itself. But 2nd thread can so it sleeps guaranteeing "2" be printed before 4, right? Right answer says it can be printed before.
Thread t will never enter synchronized block because it does not hold lock on itself.
Jeet Jain wrote:How can 4 ever print before 2? Thread t will never enter synchronized block because it does not hold lock on itself. But 2nd thread can so it sleeps guaranteeing "2" be printed before 4, right? Right answer says it can be printed before.
Thread t will never enter synchronized block because it does not hold lock on itself. But 2nd thread can ...
Matt Gottlieb wrote:
4) Once the sleep period is over, again one of two things happen - either the thread that acquired the lock continues and prints out its final print statement, or the JVM switches to the other thread. If the JVM switches to the other thread, this thread goes to sleep and the first thread will print out its final print statement.
1 3 4 2 - T1 prints 1 --> T2 prints 3 --> T1 acquires lock and goes to sleep --> T1 releases lock --> T2 acquires lock (T1 is not yet runnable) --> T2 wakes up and prints 4 --> T1 prints 2
or
1 3 4 2- T1 prints 1 --> T2 prints 3 --> T2 acquires lock and goes to sleep --> T2 releases lock --> T1 acquires lock and sleeps --> T2 prints 4 while T1 is asleep --> T1 wakes up and prints 2
3 1 2 4 - T2 prints 3 --> T1 prints 1 --> T1 acquires lock and sleeps --> T1 wakes up and goes on to print 2 --> T2 acquires lock and sleeps, wakes up and prints 4
CLUCK LIKE A CHICKEN! Now look at this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
|