如果当前线程持有指定对象的监视器锁,则线程类的 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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。