Determine which thread owns a monitor

前端 未结 4 1345
有刺的猬
有刺的猬 2020-12-06 01:50

Is there a way to tell, for a Java object, which Thread (or null) currently owns its monitor? Or at least a way to tell if the current thread owns it?

4条回答
  •  悲哀的现实
    2020-12-06 02:31

    Instead of using synchronized, you might want to take a look at ReentrantLock, especially its methods getOwner() and isHeldByCurrentThread(). It takes a bit more discipline to use, though, since you explicitly have to unlock() it, preferrably in a finally block.

提交回复
热议问题