I copied these code from http://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html
I made slight changes:
The output is:
run:
bow() methode invoked on Alphonse object
bowBack() methode invoked on Gaston object
bow() methode invoked on Gaston object
bowBack() methode invoked on Alphonse object
BUILD SUCCESSFUL (total time: 0 seconds)
Now, if you uncomment line 25: Thread.sleep(50);
the output will be
run:
bow() methode invoked on Alphonse object
bow() methode invoked on Gaston object
...... Deadlock ......
The first case (with no deadlock) is not a problem for me. The second case where deadlock happened when uncommenting Thread.sleep(50) is the problem.
The way these threads work (violates) the rule(s) that I understand about threads.
1- On a single processor machine only one thread can actually be running at a time
2- Each object in Java is said to have a lock.
3- A thread entering a synchronized method gains the lock on the object that contains the method
4- No other thread can access any synchronized method in that object until the lock is released - by thread completing the processing inside the method.
.......
When the start() method is sent to both threads alphonse.bow(gaston) & gaston.bow(alphonse), they are both moved to the runnable state.
name the threads
Thread1: alphonse.bow(gaston)
Thread2: gaston.bow(alphonse)
If the selected thread say Thread1 by the processor to be moved to the running state is alphonse.bow(gaston), then it is running, and no other thread can start running until Thread1 completes the processing of the method bow() on alphonse object.
The processing steps is to print: bow() methode invoked on Alphonse object
Then sleep(50) - note that sleep() will not move Thread1 to the blocked state because the method is labelled with synchronized .
Finally invoke gaston.bowBack(alphonse)
It is expected that gaston.bowBack(alphonse) completes and prints: bowBack() methode invoked on Gaston object (which didn't happen)
and at this point Thread1 completes processing method bow() and Thread1 moved to the finished state (which didn't happen).
But instead of that, another thread Thread2 had moved to the running state before Thread1 completed processing of method bow() which violates rule 4. (I need explanation?)
So Thread2 gaston.bow(alphonse) is now running
The processing of gaston.bow(alphonse) is to print: bow() methode invoked on Gaston object
Then sleep(50)
Finally invoke alphonse.bowBack(gaston) which didn't proceed. (why?)
Thank you