why does the following code result in deadlock

时光怂恿深爱的人放手 提交于 2019-12-02 02:01:13

lock1 is locked twice: once in lockFirst and again in unlockFirst (lock1.tryLock()), but unlocked only once in unlockFirst.

ReentrantLock has a hold count. See ReentrantLock. If you call tryLock, even if it's already held by the current thread it still increments the hold count. So, you increment it twice, but only decrement it once.

Having locked lock1, you never fully unlock it. If the thread holds lock1 when it calls unlockFirst(), it will still hold lock1 when the function returns.

If you call lock1.lock() followed by a successful lock1.tryLock(), you need to call lock1.unlock() twice to completely release the lock. Your code doesn't do that, hence the deadlock.

You have a static Locker shared across all threads.

At some point a thread is going to try to tryLock() while the lock is already held by another thread.

edit: incorrect, ignore.

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