如果當前線程在指定對象上保存監視器鎖,則Thread
類的holdLock()
方法返回true
。
語法
public static boolean holdsLock(Object obj)
參數
obj
:它定義了測試鎖所有權的對象
返回
當且僅當當前線程在指定對象上保存監視器鎖時,它才返回true
。 否則,它返回false
。
示例
NullPointerException
:如果obj
為null
,則拋出此異常。
示例
public class JavaHoldLockExp implements Runnable
{
public void run()
{
// print currently executing thread
System.out.println("Currently executing thread is: " + Thread.currentThread().getName());
// returns true if the current thread holds the lock on the specified object
System.out.println("Does thread holds lock? " + Thread.holdsLock(this));
synchronized (this)
{
System.out.println("Does thread holds lock? " + Thread.holdsLock(this));
}
}
public static void main(String[] args)
{
JavaHoldLockExp g1 = new JavaHoldLockExp();
// create a thread
Thread t1 = new Thread(g1);
// this will call run() function
t1.start();
}
}
執行上面示例代碼,得到以下結果:
Currently executing thread is: Thread-0
Does thread holds lock? false
Does thread holds lock? true
上一篇:
Java Runtime類
下一篇:無