why this synchronized method is not working as expected?

前端 未结 2 1368
庸人自扰
庸人自扰 2020-12-11 09:58

Could someone explain two me why these to codes dont output the same results (the only difference between two codes is in the run() method) ?

NB: the first code seem

相关标签:
2条回答
  • 2020-12-11 10:42

    First Code

    The thing is that you have 3 instances of a thread and each threads runs it's own synchronized instance of the method run(). But there is always only one thread that is wating to be synchronized to it's own run() method, so it will run whenever the threads wants it to run. This results in no synchronization at all.

    Second Code

    You have also 3 instances of a thread, but they share a reference to the letter object. Therefore if you lock this reference, the threads will exclude each other and the code runs as expected.

    Additional Information

    This post explains pretty good why the first solution doesn't work: Should you synchronize the run method? Why or why not?

    0 讨论(0)
  • 2020-12-11 10:44

    When you want to synchronize two threads you must lock on a shared resource by all threads. Synchronizing in the run method(or any instance method in thread class) each thread locks it's own method resulting no synchronization at all.

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