Why exactly did you expect this program to make your computer levitate or freeze?
What happens is that first the first thread runs, it grabs the lock, and when it's finished, it releases the lock and the second thread runs. The second thread has to wait on the lock because the first thread has locked it. Static synchronized methods synchronize on the class object of the class that they're in. So this:
Thanks Jesper. Yes, it works as you say. However K&B book suggests they will block each other becasue "they (both threads) lock on the same Class instance". So is it a mistake in the book or my misinterpretation of blocking each other meaning non of this threads will be able to execute the method, because both will wait for each other to grab and execute the method?
Ok, subquestion. How could I modify this code so both threads actually will block each other?
Joined: May 09, 2010
I think I understand my mistake. In K&B book blocking actually means getting a lock and holding it when till the method execution is finished. So thats a good thing, thats what we want. Where as in the next example on the same page quote is: "synchronized, satic and non-static method will not block each other, ever". And thats bad, becase it defeats our intention of synchronization.
My mistake was misinterpretation of a word "blocking". I had in mind "deadlock".