Java Thread holdsLock() 方法



描述

Java Thread holdsLock() 方法当且仅当当前线程持有指定对象的监视器锁时返回 true。

声明

以下是 java.lang.Thread.holdsLock() 方法的声明

public static boolean holdsLock(Object obj)

参数

obj − 这是要测试锁所有权的对象。

返回值

如果当前线程持有指定对象的监视器锁,则此方法返回 true。

异常

NullPointerException − 如果 obj 为 null。

示例:检查线程是否持有锁为真

以下示例显示了 Java Thread holdsLock() 方法的使用。在此程序中,我们创建了一个类 ThreadDemo。在 main 方法中,我们创建了一个新线程并使用 start() 方法启动它。在 run() 方法中,我们使用 holdsLock() 方法打印持有锁的状态。由于在同步块中,holdsLock() 方法返回 true。

package com.tutorialspoint;

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 */
      synchronized (this) {
         System.out.println("Holds Lock = " + Thread.holdsLock(this));
      }
   }

   public static void main(String[] args) {
      new ThreadDemo();
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Holds Lock = true

示例:检查线程是否持有锁为假

以下示例显示了 Java Thread holdsLock() 方法的使用。在此程序中,我们创建了一个类 ThreadDemo。在 main 方法中,我们创建了一个新线程并使用 start() 方法启动它。在 run() 方法中,我们使用 holdsLock() 方法打印持有锁的状态。由于不在同步块中,holdsLock() 方法返回 false。

package com.tutorialspoint;

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));  
   }

   public static void main(String[] args) {
      new ThreadDemo();
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Holds Lock = false
java_lang_thread.htm
广告

© . All rights reserved.