Java - Syncronized Thread - Output in wrong order

前端 未结 3 1588
傲寒
傲寒 2021-01-19 06:40

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

相关标签:
3条回答
  • 2021-01-19 07:14

    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.

    0 讨论(0)
  • 2021-01-19 07:23

    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.

    0 讨论(0)
  • 2021-01-19 07:41

    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.

    0 讨论(0)
提交回复
热议问题