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

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

 2009-09-17 00:00:00 来源:WEB开发网   
核心提示: 测试类 Java代码publicclassMain{publicstaticvoidmain(String[]args){Datadata=newData(10);newReaderThread(data).start();newReaderThread(data).start();newRea

测试类

Java代码   

public class Main { 
  public static void main(String[] args) { 
    Data data = new Data(10); 
    new ReaderThread(data).start(); 
    new ReaderThread(data).start(); 
    new ReaderThread(data).start(); 
    new ReaderThread(data).start(); 
    new ReaderThread(data).start(); 
    new ReaderThread(data).start(); 
    new WriterThread(data, "ABCDEFGHIJKLMNOPQRSTUVWXYZ").start(); 
    new WriterThread(data, "abcdefghijklmnopqrstuvwxyz").start(); 
  } 
}

jdk1.5新特性读写锁

Java代码

public class Data {  
  private final char[] buffer;  
  //private final ReadWriteLock lock = new ReadWriteLock();  
  //读写锁  
     private ReadWriteLock lock = new ReentrantReadWriteLock();  
  
     //生成读锁  
  private Lock readLock = lock.readLock();  
     //生成写锁  
  private Lock writeLock = lock.writeLock();  
  
  public Data(int size) {  
    this.buffer = new char[size];  
    for (int i = 0; i < buffer.length; i++) {  
      buffer[i] = '*';  
    }  
  }  
  
  public char[] read() throws InterruptedException {  
    readLock.lock();  
    try {  
      return doRead();  
    } finally {  
      readLock.unlock();  
    }  
  }  
  
  public void write(char c) throws InterruptedException {  
    writeLock.lock();  
    try {  
      doWrite(c);  
    } finally {  
      writeLock.unlock();  
    }  
  }  
  
  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) {  
    }  
  } 

上一页  1 2 3 4 

Tags:线程 设置 模式

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