我有一个名为“Channel”的类,定义了两个方法:
class Channel {
void read(){...}
void write(){...}
}
在多线程环境中使用此类的实例。多个线程定期从通道读取,而一个线程周期性地写入它。读操作是线程安全的,因此可以同时进行多次读操作。但是,一旦写入操作开始,必须阻止读取线程,直到写入操作完成。必须尽可能快地保持读取操作并避免消耗资源的同步例程。
实施此类行为的最合适模式是什么?也许java类或库有帮助吗?
答案 0 :(得分:8)
使用ReadWriteLock。它将允许串行写入发生并发读取。为了进一步满足您的要求,获取writeLock
将阻止任何readLock
在后续发布之前取得进展。
class Channel {
final ReadWriteLock lock = new ReentrantReadWriteLock();
void read(){
lock.readLock().lock();
try{
}finally{
lock.readLock().unlock();
}
}
void write(){
lock.writeLock().lock();
try{
}finally{
lock.writeLock().unlock();
}
}
}
答案 1 :(得分:1)
为了好玩,这是使用新的Java 7 try-with-resources功能的实现。
class RWLock {
class ACLock extends ReentrantLock implements AutoCloseable {
public void close() {
this.unlock();
}
}
private ACLock readLock = ACLock();
private ACLock writeLock = ACLock();
private int numReaders = 0
public AutoCloseable write() {
readLock.lock();
writeLock.lock();
return new AutoCloseable() {
public void close() {
writeLock.close();
readLock.close();
}
}
}
public AutoCloseable read() {
try (ACLock read = readLock.acquire()) {
if (numReaders == 0) {
writeLock.lock();
}
numReaders++;
}
return new AutoCloseable() {
public void close() {
numReaders--;
if (numReaders == 0) {
writeLock.unlock();
}
}
}
}
// Here's how you use them
public static void main(String[] args) {
RWLock lock = RWLock();
try (AutoCloseable lock = RWLock.read()) {
// Do some readin'
}
try (AutoCloseable lock = RWLock.write()) {
// Do some writin'
}
}
}