WEB开发网
开发学院软件开发Java 多线程设置模式 -- Read-Write Lock Pattern 阅读

多线程设置模式 -- Read-Write Lock Pattern

 2009-09-17 00:00:00 来源:WEB开发网   
核心提示://读写锁 Java代码publicfinalclassReadWriteLock{privateintreadingReaders=0;//(A)...实际正在读取的执行绪数量privateintwaitingWriters=0;//(B)...正在等待写入的执行绪数量privateintwritingWriters

//读写锁

Java代码   

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 { 
     waitingWriters--;          // (B)正在等待写入的线程数量减1 
    } 
    writingWriters++;            // (C)实际正在写入的线程数量加1 
  } 
 
  public synchronized void writeUnlock() { 
    writingWriters--;            // (C)实际正在写入的线程数量减 
    preferWriter = false; 
    //唤醒读写线程 
    notifyAll(); 
  } 
}

1 2 3 4  下一页

Tags:线程 设置 模式

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接