當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Thread holdLock()用法及代碼示例


如果當前線程持有指定對象的監視器鎖,則線程類的 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 holdLock() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。