I\'m reading Java The Complete Reference(9th Edition) after year of fooling around with Java. Been happy with the book so far but I now have a really strange problem with sy
The short answer is that the only thing your synchronized
block guarantees is that your 3 calls to Callme.call
will be mutually exclusive - you won't (for example) end up with all 3 of your threads in the Thread.sleep
call simultaneously. It doesn't guarantee anything about the order in which the three calls will occur, and in fact it would be possible (though unlikely) that running your unmodified code multiple times could result in your 3 words being output in any order on any particular run.
When multiple threads are waiting on a lock, there is no guarantee as to which thread the lock will be given once its released. The docs does not specify how this order is handled, but its also not random. I cant say for certain, but it seems the default implementation gives the lock in a LIFO style (Last in first out) and thats why world is outputted first. Give it a try with some more objects.
When you start multiple threads they all need some time to spin up, java does not garantee in which order this completes. The first thread which reaches the call() method will execute it, then the next. There is nothing in your code which enforces a sequence of that.