线程读写文件

多进程读写文件:一个进程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();   
  }   
}  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值