When running the program as it is, two threads -when started- are competing to enter method swim(), we cannot determine which thread will enter the method first. Since swim() is not synchronized, it means the running thread doesn't seize the lock of Test class, meaning it is possible that the thread doesn't finish executing swim() and waits for its next CPU slice to return back and continue executing, and while waiting there the other thread(s) can enter swim().
Another possibility is that the entering thread finishes executing swim() before even the second thread get started.
By synchronizing swim(), the entering thread seizes the lock of class Test, and it doesn't release the lock until it finishes executing swim(), therefore alternating between threads to execute swim() is out of question.
|
Oracle Certified Professional Java Programmer
Author:
JavaChamp TeamSenior Java Developer
QuizOver.com
Germany
Access: |