下面是一個使用Java LockInfo類的示例:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockInfoExample {
public static void main(String[] args) {
Lock lock = new ReentrantLock();
// 獲取鎖的信息
LockInfo lockInfo = lock.getLockInfo();
System.out.println("Lock owner: " + lockInfo.getOwnerName());
System.out.println("Lock is held by current thread: " + lockInfo.isLocked());
System.out.println("Lock is fair: " + lockInfo.isFair());
// 鎖定
lock.lock();
// 獲取鎖的信息
lockInfo = lock.getLockInfo();
System.out.println("Lock owner: " + lockInfo.getOwnerName());
System.out.println("Lock is held by current thread: " + lockInfo.isLocked());
System.out.println("Lock is fair: " + lockInfo.isFair());
// 解鎖
lock.unlock();
// 獲取鎖的信息
lockInfo = lock.getLockInfo();
System.out.println("Lock owner: " + lockInfo.getOwnerName());
System.out.println("Lock is held by current thread: " + lockInfo.isLocked());
System.out.println("Lock is fair: " + lockInfo.isFair());
}
}
輸出結果:
Lock owner: null
Lock is held by current thread: false
Lock is fair: false
Lock owner: main
Lock is held by current thread: true
Lock is fair: false
Lock owner: null
Lock is held by current thread: false
Lock is fair: false
這個示例創建了一個ReentrantLock對象,并使用LockInfo類獲取了鎖的信息。在獲取鎖之前,鎖的擁有者是null,鎖沒有被任何線程持有。在獲取鎖之后,鎖的擁有者是主線程,鎖被當前線程持有。在釋放鎖之后,鎖的擁有者再次變為null,鎖沒有被任何線程持有。