This content has been marked as final. Show 6 replies
Because the bowback and bow methods are synchronized, only one thread can run either of them at the same time. When both threads are in bow, neither can enter bowback, since there's already a thread running synchronized code on both Friends. So they both wait indefinitely for the other to finish, but neither can finish until the other does.
The first thread (T1) locks alphonse to invoke his bow method. While still holding that lock, it tries to lock gaston to invoke his bowback method.
If T2 has already started gaston's bow method, then T1 cannot continue until T2 releases gaston's lock. But T2 can't release it until it gets alphonse's lock to call alphose.bowback. But T2 can't get that lock until T1 releases it, but T1 can't release it until T2 proceeds, which can't happen until T1 proceeds...
T1 holds lock A and is waiting on lock B.
T2 holds lock B and is waiting on lock A.
I didn't get why there is deadlock, because as oneNo, it doesn't lock the method. It obtains an object's lock.
thread locks the 'bow' function,
T1 gets O1's lock, and then needs O2's lock in order to continue.
T2 gets O2's lock, and then needs O1's lock to continue.
alphonse.bow gets alphonse's lock, and, while holding it, calls gaston.bowback, which requires gaston's lock, but which gaston is already holding, waiting for alphonse's lock, which alphonse is already holding.
but how come the two of them enter bow, if it isBecause there are two different objects. One thread enters the sync block (and locks out any other threads) of object one, and the other thread enters the sync block (and locks out any other threads) of object 2. Then without either releasing their grip on the locks, they each try to enter the other object's lock, which they can't do. So they just sit and wait forever.