Deadlocks and Synchronized methods

前端 未结 3 1033
太阳男子
太阳男子 2020-12-11 06:36

I\'ve found one of the code on Stack Overflow and I thought it is pretty similar to what I am facing but I still don\'t understand why this would enter a deadlock. The examp

3条回答
  •  攒了一身酷
    2020-12-11 07:03

    synchronized places a lock on the object that must be acquired before the methods or codeblocks can execute. Because it locks entire objects, it is an inelegant tool that sometimes looks pretty easy to use, but gives deadlocks like this, where no actual contested data is being read or written.

    a.method(b) locks the a object. b.method(a) locks the b object. And neither thread of execution can continue on to calling b.last() or a.last(), because they are both waiting for the other object to release its lock.

提交回复
热议问题