包java.lang.Thread.holdLock(Object obj)中提供了此方法。
此方法用于将当前线程锁定在方法中给定的指定对象上。
此方法是静态的,因此我们也可以使用类名访问此方法。
此方法的返回类型为boolean,因此如果返回true表示该方法中要锁定在给定对象上的当前线程,则返回true或false,否则返回false。
如果对象为null,则此方法引发异常。
语法:
static boolean holdLock(Object o){
}参数:
我们仅在Thread方法中将一个对象作为参数传递,即Object obj,以便在其上测试锁所有权的obj。
返回值:
此方法的返回类型为Boolean,如果此线程在方法中给定对象上的监视器锁定,则返回true,否则返回false。
holdLock()方法示例/* We will use Thread class methods so we are importing
the package but it is not mandate because
it is imported by default
*/
import java.lang.Thread;
class HoldLock extends Thread {
static Thread t1;
//覆盖run()Thread类
public void run() {
//我们将显示当前线程的名称
System.out.println("The name of the Current thread is: " + Thread.currentThread().getName());
//此方法返回true
//指定对象上的锁
//这里我们没有在同步块中锁定对象t1-
System.out.println("Is thread t1 holds lock here? " + Thread.holdsLock(t1));
//这里我们将对象t1锁定在同步块中
synchronized(t1) {
System.out.println("Is thread t1 holds lock here? " + Thread.holdsLock(t1));
}
}
public static void main(String[] args) {
//创建HoldLock类的对象
HoldLock lock = new HoldLock();
//创建线程对象t1-
t1 = new Thread(lock);
//调用start()方式
t1.start();
}
}输出结果
E:\Programs>javac HoldLock.java E:\Programs>java HoldLock The name of the Current thread is: Thread-1 Is thread t1 holds lock here ? false Is thread t1 holds lock? true