日期:2014-05-20 浏览次数:20738 次
public final class ReadWriteLock { private int readingReaders = 0; // (A)...实际正在读取的执行绪数量 private int waitingWriters = 0; // (B)...正在等待写入的执行绪数量 private int writingWriters = 0; // (C)...实际正在写入的执行绪数量 private boolean preferWriter = true; // 写入优先的话,值为true public synchronized void readLock() throws InterruptedException { while (writingWriters > 0 || (preferWriter && waitingWriters > 0)) { wait(); } readingReaders++; // (A)实际正在读取的线程数量加1 } public synchronized void readUnlock() { readingReaders--; // (A)实际正在读取的线程数量减1 preferWriter = true; notifyAll(); } public synchronized void writeLock() throws InterruptedException { waitingWriters++; // (B)正在等待写入的线程数量加1 try { while (readingReaders > 0 || writingWriters > 0) { wait(); } } finally {1 waitingWriters--; // (B)正在等待写入的线程数量减1 } writingWriters++; // (C)实际正在写入的线程数量加1 } public synchronized void writeUnlock() { writingWriters--; // (C)实际正在写入的线程数量减 preferWriter = false; notifyAll(); } } // 数据类 public class Data { private final char[] buffer; private final ReadWriteLock lock = new ReadWriteLock(); public Data(int size) { this.buffer = new char[size]; for (int i = 0; i < buffer.length; i++) { buffer[i] = '*'; } } public char[] read() throws InterruptedException { lock.readLock(); try { return doRead(); } finally { lock.readUnlock(); } } public void write(char c) throws InterruptedException { lock.writeLock(); try { doWrite(c); } finally { lock.writeUnlock(); } } private char[] doRead() { char[] newbuf = new char[buffer.length]; for (int i = 0; i < buffer.length; i++) { newbuf[i] = buffer[i]; } slowly(); return newbuf; } private void doWrite(char c) { for (int i = 0; i < buffer.length; i++) { buffer[i] = c; slowly(); } } private void slowly() { try { Thread.sleep(50); } catch (InterruptedException e) { } } }