我如何在ReentrantReadWriteLock ReadLock和WriteLock上创建一个包装器

时间:2011-12-05 21:36:46

标签: java multithreading locking locks reentrantreadwritelock

我有ReentrantReadWriteLockReentrantReadWriteLock包含ReadLock和WriteLock作为子类。

I want to extend this ReadLock and WriteLock by my custom classes as 

DummyReadLock and DummyWriteLock.

然后我必须能够做类似下面的事情

 final Lock lock = new DummyReadLock.readLock();

final Lock lock = new DummyWriteLock.writeLock();

是否有可能实现这一目标。?

2 个答案:

答案 0 :(得分:0)

你可以:

class DummyReadLock extends ReentrantReadWriteLock.ReadLock {

    private ReentrantReadWriteLock.ReadLock readLock;

    // inherited constructor
    protected DummyRLock(ReentrantReadWriteLock rwlock) {
        super(rwlock);
        this.readLock = rwlock.readLock(); 
    }

    public ReentrantReadWriteLock.ReadLock readLock() {
        return readLock;
    }       
}

答案 1 :(得分:0)

是的,这应该是可能的。我不确定你为什么要这样做,但是下面的代码会扩展ReadLock,例如。

public class DummyReadLock extends ReentrantReadWriteLock.ReadLock
{
  public DummyReadLock(ReentrantReadWriteLock arg0)
  {
    super(arg0);
  }
}

请注意,ReadLock的构造函数需要使用ReentrantReadWriteLock作为参数,因此您无法完全按照示例中的说明调用它。