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
廣告