ReentrantLock 類的 getQueueLength() 方法返回等待獲取鎖的線程數。該值是近似值,因為線程數可以在遍曆內部數據結構時動態更改。它用於監視狀態。
用法
public final int getQueueLength()
參數
沒有傳遞參數。
返回
等待此鎖的估計線程數
拋出
不會拋出異常。
例子1
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockgetQueueLengthExample1 {
public static void main(String[] args) {
ReentrantLock lock=new ReentrantLock();
MyRunnableClass90 myRnbl=new MyRunnableClass90(lock);
new Thread(myRnbl,"Thread-1").start();
}
}
class MyRunnableClass90 implements Runnable{
ReentrantLock lock;
public MyRunnableClass90(ReentrantLock lock) {
this.lock=lock;
}
public void run(){
int i;
Thread t1 = new Thread();
Thread t2 = new Thread();
t1.holdsLock(t1);
t2.holdsLock(t2);
for(i=5;i<=10;i++) {
if(i==7)
{
System.out.println(" getQueueLength = "+lock.getQueueLength()+" ");
}
if(i==5)
System.out.println(Thread.currentThread().getName()
+" has released the lock.");
}
}
}
輸出:
Thread-1 has released the lock. getQueueLength = 0
例子2
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockgetQueueLengthExample2 {
public static void main(String[] args) {
ReentrantLock lock=new ReentrantLock();
MyRunnableClass10 myRnbl=new MyRunnableClass10(lock);
new Thread(myRnbl,"ThreadA").start();
new Thread(myRnbl,"ThreadB").start();
new Thread(myRnbl,"ThreadC").start();
}
}
class MyRunnableClass10 implements Runnable{
ReentrantLock lock;
public MyRunnableClass10(ReentrantLock lock) {
this.lock=lock;
}
public void run(){
lock.lock();
System.out.println(Thread.currentThread().getName()
+" has got the lock.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("getQueueLength = "+lock.getQueueLength());
lock.unlock();
}
}
輸出:
ThreadB has got the lock. getQueueLength = 2 ThreadA has got the lock. getQueueLength = 1 ThreadC has got the lock. getQueueLength = 0
相關用法
- Java ReentrantLock lock()用法及代碼示例
- Java ReentrantLock toString()用法及代碼示例
- Java ReentrantLock tryLock()用法及代碼示例
- Java ReentrantLock isHeldByCurrentThread()用法及代碼示例
- Java ReentrantLock isLocked()用法及代碼示例
- Java ReentrantLock getHoldCount()用法及代碼示例
- Java ReentrantLock isFair()用法及代碼示例
- Java ReentrantLock hasQueuedThread()用法及代碼示例
- Java ReentrantLock getOwner()用法及代碼示例
- Java ReentrantLock hasQueuedThreads()用法及代碼示例
- Java ReentrantLock lockInterruptibly()用法及代碼示例
- Java Reader read(CharBuffer)用法及代碼示例
- Java Reader markSupported()用法及代碼示例
- Java Reader ready()用法及代碼示例
- Java ResolverStyle valueOf()用法及代碼示例
- Java ResourceBundle containsKey()用法及代碼示例
- Java ResourceBundle getString()用法及代碼示例
- Java ResourceBundle getKeys()用法及代碼示例
- Java ResourceBundle clearCache()用法及代碼示例
- Java Reader close()用法及代碼示例
注:本文由純淨天空篩選整理自 Java Reentrant getQueueLength() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。