Why is Java synchronized not working as expected?

浪子不回头ぞ 提交于 2019-12-02 04:03:37

Each A instance has its own B instance. The method addNew is an instance method of B. Therefore, the lock acquired implicitly during calls to addNew is the lock on the receiver B instance. Each thread is calling addNew on a different B, and therefore locking on different locks.

If you want all B instances to use a common lock, create a single shared lock, and acquire it in the body of addNew.

Both A objects have their own B object. You need them to share a B so the synchronization can have an effect.

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