如果當前線程持有指定對象的監視器鎖,則線程類的 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 Thread toString()用法及代碼示例
- Java Thread interrupted()用法及代碼示例
- Java Thread setDefaultUncaughtExceptionHandler()用法及代碼示例
- Java Thread suspend()用法及代碼示例
- Java Thread destroy()用法及代碼示例
- Java Thread getContextClassLoader()用法及代碼示例
- Java Thread setContextClassLoader()用法及代碼示例
- Java Thread sleep()用法及代碼示例
- Java Thread getThreadGroup()用法及代碼示例
- Java Thread isInterrupted()用法及代碼示例
- Java Thread enumerate()用法及代碼示例
- Java Thread notify()用法及代碼示例
- Java Thread resume()用法及代碼示例
- Java Thread activeCount()用法及代碼示例
- Java Thread isDaemon()用法及代碼示例
- Java Thread setDaemon()用法及代碼示例
- Java Thread getId()用法及代碼示例
- Java Thread setName()用法及代碼示例
- Java Thread getDefaultUncaughtExceptionHandler()用法及代碼示例
- Java Thread getState()用法及代碼示例
注:本文由純淨天空篩選整理自 Java Thread holdLock() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。