why this synchronized method is not working as expected?

时光总嘲笑我的痴心妄想 提交于 2019-11-28 12:44:30
L.Butz

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?

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!