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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。