Java.lang.Thread.holdsLock() 方法
描述
java.lang.Thread.holdsLock() 方法当且仅当当前线程持有指定对象的监视器锁时才返回 true。
声明
以下是 java.lang.Thread.holdsLock() 方法的声明。
public static boolean holdsLock(Object obj)
参数
obj − 这是测试锁定所有权的对象。
返回值
如果当前线程持有指定对象的监视器锁,则此方法返回 true。
异常
NullPointerException − 如果 obj 为 null。
示例
下面的例子展示了 java.lang.Thread.holdsLock() 方法的使用。
package com.tutorialspoint;
import java.lang.*;
public class ThreadDemo implements Runnable {
Thread th;
public ThreadDemo() {
th = new Thread(this);
// this will call run() function
th.start();
}
public void run() {
/* returns true if and only if the current thread holds the
monitor lock on the specified object */
System.out.println("Holds Lock = " + Thread.holdsLock(this));
synchronized (this) {
System.out.println("Holds Lock = " + Thread.holdsLock(this));
}
}
public static void main(String[] args) {
new ThreadDemo();
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
Holds Lock = false Holds Lock = TRUE

