我使用
创建一个java.util.concurrent.locks.ReentrantReadWriteLock
new java.util.concurrent.locks.ReentrantReadWriteLock().readLock()
然后我将方法作为 Lock
接口(interface)传递给方法
method(Lock lock)
现在我想知道当前线程拥有多少个读锁。我怎样才能实现这个目标?
我无法将其再次转换为 ReentrantReadWriteLock 。我应该怎么办?我怎样才能得到这个计数?
最佳答案
要获取ReentrantReadWriteLock上的读锁计数,需要调用lock.getReadHoldCount()
要单独从 ReadLock 获取此信息,您需要获取“sync”字段并通过反射调用“getReadHoldCount()”。
<小时/>使用反射访问锁的示例如下。
static void printOwner(ReentrantLock lock) {
try {
Field syncField = lock.getClass().getDeclaredField("sync");
syncField.setAccessible(true);
Object sync = syncField.get(lock);
Field exclusiveOwnerThreadField = AbstractOwnableSynchronizer.class.getDeclaredField("exclusiveOwnerThread");
exclusiveOwnerThreadField.setAccessible(true);
Thread t = (Thread) exclusiveOwnerThreadField.get(sync);
if (t == null) {
System.err.println("No waiter?");
} else {
CharSequence sb = Threads.asString(t);
synchronized (System.out) {
System.out.println(sb);
}
}
} catch (NoSuchFieldException e) {
throw new AssertionError(e);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
}
<小时/>
您可以做的是创建一个包装器。
class MyLock implements Lock {
private final ReentrantReadWriteLock underlying; // set in constructor
public ReentrantReadWriteLock underlying() { return underlying; }
public void lock() { underlying.readLock().lock(); }
}
关于java - 有没有办法从 java.util.concurrent.locks.ReentrantReadWriteLock$ReadLock 获取 java.util.concurrent.locks.ReentrantReadWriteLock 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8324278/