线程读写文件

多进程读写文件:一个进程A写文件file,另一个进程B读文件file
Doug Lea 在他的书中提供一个示例代码
ReadWrite 为抽象类,允许并发的读操作,不允许并发的写操作,也不允许读写同时进行。
可以扩展ReadWrite为SingleFileReadWrite 实现 doRead和doWrite方法来读写文件
线程A和线程B使用同一个SingleFileReadWrite 实例

 

 

SingleFileReadWrite rw;
threadB rw.read();
threadA rw.write();

Java代码 

 

abstract class ReadWrite {   
 protected int activeReaders = 0;  // threads executing read   
 protected int activeWriters = 0;  // always zero or one   
  
 protected int waitingReaders = 0; // threads not yet in read   
 protected int waitingWriters = 0; // same for write   
  
 protected abstract void doRead(); // implement in subclasses   
 protected abstract void doWrite();   
  
 public void read() throws InterruptedException {   
  beforeRead();   
  try   { doRead(); }   
  finally { afterRead(); }   
 }   
  
 public void write() throws InterruptedException {   
  beforeWrite();   
  try     { doWrite(); }   
  finally { afterWrite(); }   
 }   
 protected boolean allowReader() {   
  return waitingWriters == 0 && activeWriters == 0;   
 }   
  
 protected boolean allowWriter() {   
  return activeReaders == 0 && activeWriters == 0;   
 }   
  
 protected synchronized void beforeRead()   
  throws InterruptedException {   
   ++waitingReaders;   
   while (!allowReader()) {   
    try { wait(); }   
    catch (InterruptedException ie) {   
      --waitingReaders; // roll back state   
      throw ie;   
    }   
  }   
  --waitingReaders;   
  ++activeReaders;   
 }   
  
 protected synchronized void afterRead()  {   
  --activeReaders;   
  notifyAll();   
 }   
  
 protected synchronized void beforeWrite()   
  throws InterruptedException {   
   ++waitingWriters;   
   while (!allowWriter()) {   
    try { wait(); }   
    catch (InterruptedException ie) {   
     --waitingWriters;   
     throw ie;   
    }   
   }   
   --waitingWriters;   
   ++activeWriters;   
 }   
  
 protected synchronized void afterWrite() {   
  --activeWriters;   
  notifyAll();   
  }   
}  

 

你可能感兴趣的:(多线程,IE)