2015年9月25日星期五

实现读写锁

Mulilple thread problem. When a reader is reading:.
CALL
1.readlock()
2. to do something
3. readunlcok()  (when the reader completes reading)

when a writer is writing:
CALL
1. writelock()
2. to do something
3. writeunlock() (complete writing). 1

public class Lock {

private int readingReaders = 0;

private int writingWriters = 0;

private int waitingWriters = 0;

private boolean writerFirst = true; // 写入优先

public synchronized void readLock() {
try {
while (writingWriters > 0 || (writerFirst && waitingWriters > 0)) {
wait();
}
} catch (InterruptedException e) {
}

readingReaders++;
}

public synchronized void readUnLock() {
readingReaders--;
writerFirst = true;
notifyAll();
}

public synchronized void writeLock() {
waitingWriters++;
try {
while (readingReaders > 0 || writingWriters > 0) {
wait();
}
} catch (InterruptedException e) {
} finally {
waitingWriters--;
}

writingWriters++;
}

public synchronized void writeUnLock() {
writingWriters--;
writerFirst = false;
notifyAll();
}

public static void main(String args[]) {

}
}

没有评论:

发表评论