如果當前執行緒在指定物件上儲存監視器鎖,則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