当前位置: 移动技术网 > IT编程>开发语言>Java > PipedWriter和PipedReader源码分析_动力节点Java学院整理

PipedWriter和PipedReader源码分析_动力节点Java学院整理

2019年07月22日  | 移动技术网IT编程  | 我要评论

pipedwriter和pipedreader源码分析

1. pipedwriter 源码(基于jdk1.7.40) 

package java.io;
 public class pipedwriter extends writer {
   // 与pipedwriter通信的pipedreader对象
   private pipedreader sink;
   // pipedwriter的关闭标记
   private boolean closed = false;
   // 构造函数,指定配对的pipedreader
   public pipedwriter(pipedreader snk) throws ioexception {
     connect(snk);
   }
   // 构造函数
   public pipedwriter() {
   }
   // 将“pipedwriter” 和 “pipedreader”连接。
   public synchronized void connect(pipedreader snk) throws ioexception {
     if (snk == null) {
       throw new nullpointerexception();
     } else if (sink != null || snk.connected) {
       throw new ioexception("already connected");
     } else if (snk.closedbyreader || closed) {
       throw new ioexception("pipe closed");
     }
     sink = snk;
     snk.in = -1;
     snk.out = 0;
     // 设置“pipedreader”和“pipedwriter”为已连接状态
     // connected是pipedreader中定义的,用于表示“pipedreader和pipedwriter”是否已经连接
     snk.connected = true;
   }
   // 将一个字符c写入“pipedwriter”中。
   // 将c写入“pipedwriter”之后,它会将c传输给“pipedreader”
   public void write(int c) throws ioexception {
     if (sink == null) {
       throw new ioexception("pipe not connected");
     }
     sink.receive(c);
   }
   // 将字符数组b写入“pipedwriter”中。
   // 将数组b写入“pipedwriter”之后,它会将其传输给“pipedreader”
   public void write(char cbuf[], int off, int len) throws ioexception {
     if (sink == null) {
       throw new ioexception("pipe not connected");
     } else if ((off | len | (off + len) | (cbuf.length - (off + len))) < ) {
       throw new indexoutofboundsexception();
     }
     sink.receive(cbuf, off, len);
   }
   // 清空“pipedwriter”。
   // 这里会调用“pipedreader”的notifyall();
   // 目的是让“pipedreader”放弃对当前资源的占有,让其它的等待线程(等待读取pipedwriter的线程)读取“pipedwriter”的值。
   public synchronized void flush() throws ioexception {
     if (sink != null) {
       if (sink.closedbyreader || closed) {
         throw new ioexception("pipe closed");
       }
       synchronized (sink) {
         sink.notifyall();
       }
     }
   }
   // 关闭“pipedwriter”。
   // 关闭之后,会调用receivedlast()通知“pipedreader”它已经关闭。
   public void close() throws ioexception {
     closed = true;
     if (sink != null) {
       sink.receivedlast();
     }
   }
 }

2. pipedreader 源码(基于jdk1.7.40)    

package java.io;
  public class pipedreader extends reader {
    // “pipedwriter”是否关闭的标记
    boolean closedbywriter = false;
    // “pipedreader”是否关闭的标记
    boolean closedbyreader = false;
    // “pipedreader”与“pipedwriter”是否连接的标记
    // 它在pipedwriter的connect()连接函数中被设置为true
   boolean connected = false;
   thread readside;  // 读取“管道”数据的线程
   thread writeside;  // 向“管道”写入数据的线程
   // “管道”的默认大小
  private static final int default_pipe_size = 1024;
   // 缓冲区
   char buffer[];
   //下一个写入字符的位置。in==out代表满,说明“写入的数据”全部被读取了。
   int in = -;
   //下一个读取字符的位置。in==out代表满,说明“写入的数据”全部被读取了。
   int out = ;
   // 构造函数:指定与“pipedreader”关联的“pipedwriter”
   public pipedreader(pipedwriter src) throws ioexception {
     this(src, default_pipe_size);
   }
   // 构造函数:指定与“pipedreader”关联的“pipedwriter”,以及“缓冲区大小”
   public pipedreader(pipedwriter src, int pipesize) throws ioexception {
     initpipe(pipesize);
     connect(src);
   }
   // 构造函数:默认缓冲区大小是1024字符
   public pipedreader() {
     initpipe(default_pipe_size);
   }
   // 构造函数:指定缓冲区大小是pipesize
   public pipedreader(int pipesize) {
     initpipe(pipesize);
   }
   // 初始化“管道”:新建缓冲区大小
   private void initpipe(int pipesize) {
    if (pipesize <= 0) {
       throw new illegalargumentexception("pipe size <= 0");
     }
     buffer = new char[pipesize];
   }
   // 将“pipedreader”和“pipedwriter”绑定。
   // 实际上,这里调用的是pipedwriter的connect()函数
   public void connect(pipedwriter src) throws ioexception {
     src.connect(this);
   }
   // 接收int类型的数据b。
   // 它只会在pipedwriter的write(int b)中会被调用
   synchronized void receive(int c) throws ioexception {
     // 检查管道状态
     if (!connected) {
       throw new ioexception("pipe not connected");
     } else if (closedbywriter || closedbyreader) {
       throw new ioexception("pipe closed");
     } else if (readside != null && !readside.isalive()) {
       throw new ioexception("read end dead");
     }
     // 获取“写入管道”的线程
     writeside = thread.currentthread();
     // 如果“管道中被读取的数据,等于写入管道的数据”时,
    // 则每隔1000ms检查“管道状态”,并唤醒管道操作:若有“读取管道数据线程被阻塞”,则唤醒该线程。
     while (in == out) {
       if ((readside != null) && !readside.isalive()) {
         throw new ioexception("pipe broken");
       }
       /* full: kick any waiting readers */
       notifyall();
       try {
        wait(1000);
       } catch (interruptedexception ex) {
         throw new java.io.interruptedioexception();
       }
     }
    if (in < 0) {
     in = 0;
      out = 0;
     }
     buffer[in++] = (char) c;
     if (in >= buffer.length) {
      in = 0;
     }
   }
   // 接收字符数组b。
   synchronized void receive(char c[], int off, int len) throws ioexception {
     while (--len >= ) {
      receive(c[off++]);
     }
   }
   // 当pipedwriter被关闭时,被调用
   synchronized void receivedlast() {
     closedbywriter = true;
     notifyall();
   }
   // 从管道(的缓冲)中读取一个字符,并将其转换成int类型
   public synchronized int read() throws ioexception {
     if (!connected) {
       throw new ioexception("pipe not connected");
     } else if (closedbyreader) {
       throw new ioexception("pipe closed");
     } else if (writeside != null && !writeside.isalive()
          && !closedbywriter && (in < )) {
       throw new ioexception("write end dead");
     }
     readside = thread.currentthread();
    int trials = 2;
    while (in < 0) {
       if (closedbywriter) {
         /* closed by writer, return eof */
         return -1;
       }
       if ((writeside != null) && (!writeside.isalive()) && (--trials < )) {
         throw new ioexception("pipe broken");
       }
       /* might be a writer waiting */
       notifyall();
       try {
        wait(1000);
       } catch (interruptedexception ex) {
         throw new java.io.interruptedioexception();
       }
     }
     int ret = buffer[out++];
     if (out >= buffer.length) {
      out = 0;
     }
     if (in == out) {
       /* now empty */
      in = -1;
     }
     return ret;
   }
   // 从管道(的缓冲)中读取数据,并将其存入到数组b中
   public synchronized int read(char cbuf[], int off, int len) throws ioexception {
     if (!connected) {
       throw new ioexception("pipe not connected");
     } else if (closedbyreader) {
       throw new ioexception("pipe closed");
     } else if (writeside != null && !writeside.isalive()
         && !closedbywriter && (in < 0)) {
       throw new ioexception("write end dead");
     }
    if ((off < 0) || (off > cbuf.length) || (len < 0) ||
      ((off + len) > cbuf.length) || ((off + len) < 0)) {
       throw new indexoutofboundsexception();
     } else if (len == 0) {
      return 0;
     }
     /* possibly wait on the first character */
     int c = read();
    if (c < 0) {
      return -1;
     }
     cbuf[off] = (char)c;
    int rlen = 1;
    while ((in >= 0) && (--len > 0)) {
       cbuf[off + rlen] = buffer[out++];
       rlen++;
       if (out >= buffer.length) {
       out = 0;
       }
       if (in == out) {
         /* now empty */
         in = -;
       }
     }
     return rlen;
   }
   // 是否能从管道中读取下一个数据
   public synchronized boolean ready() throws ioexception {
     if (!connected) {
       throw new ioexception("pipe not connected");
     } else if (closedbyreader) {
       throw new ioexception("pipe closed");
     } else if (writeside != null && !writeside.isalive()
          && !closedbywriter && (in < )) {
       throw new ioexception("write end dead");
     }
    if (in < 0) {
       return false;
     } else {
       return true;
     }
   }
   // 关闭pipedreader
   public void close() throws ioexception {
     in = -;
     closedbyreader = true;
   }
 }

示例

下面,我们看看多线程中通过pipedwriter和pipedreader通信的例子。例子中包括3个类:receiver.java, sender.java 和 pipetest.java

receiver.java的代码如下:  

 import java.io.ioexception;  
 import java.io.pipedreader;  
 @suppresswarnings("all")  
 /** 
  * 接收者线程 
  */  
 public class receiver extends thread {  
   // 管道输入流对象。
   // 它和“管道输出流(pipedwriter)”对象绑定,
   // 从而可以接收“管道输出流”的数据,再让用户读取。
   private pipedreader in = new pipedreader();  
   // 获得“管道输入流对象”
   public pipedreader getreader(){  
     return in;  
   }  
   @override
   public void run(){  
     readmessageonce() ;
     //readmessagecontinued() ;
   }
   // 从“管道输入流”中读取次数据
   public void readmessageonce(){  
     // 虽然buf的大小是2048个字符,但最多只会从“管道输入流”中读取1024个字符。
    // 因为,“管道输入流”的缓冲区大小默认只有1024个字符。
     char[] buf = new char[2048];  
     try {  
       int len = in.read(buf);  
      system.out.println(new string(buf,0,len));  
       in.close();  
     } catch (ioexception e) {  
       e.printstacktrace();  
     }  
   }
   // 从“管道输入流”读取>1024个字符时,就停止读取
  public void readmessagecontinued(){
    int total=0;
     while(true) {
       char[] buf = new char[];
       try {
         int len = in.read(buf);
         total += len;
         system.out.println(new string(buf,,len));
        // 若读取的字符总数>1024,则退出循环。
       if (total > 1024)
           break;
       } catch (ioexception e) {
         e.printstacktrace();
       }
     }
     try {
       in.close(); 
     } catch (ioexception e) {  
       e.printstacktrace();  
     }  
   }  
 }
 
sender.java的代码如下:
 
 import java.io.ioexception;  
  import java.io.pipedwriter;  
 @suppresswarnings("all")
 /** 
  * 发送者线程 
  */  
 public class sender extends thread {  
   // 管道输出流对象。
   // 它和“管道输入流(pipedreader)”对象绑定,
   // 从而可以将数据发送给“管道输入流”的数据,然后用户可以从“管道输入流”读取数据。
   private pipedwriter out = new pipedwriter();
   // 获得“管道输出流”对象
   public pipedwriter getwriter(){
     return out;
   }  
   @override
   public void run(){  
     writeshortmessage();
     //writelongmessage();
   }  
   // 向“管道输出流”中写入一则较简短的消息:"this is a short message" 
   private void writeshortmessage() {
     string strinfo = "this is a short message" ;
     try {
       out.write(strinfo.tochararray());
       out.close();  
     } catch (ioexception e) {  
       e.printstacktrace();  
     }  
   }
   // 向“管道输出流”中写入一则较长的消息
   private void writelongmessage() {
     stringbuilder sb = new stringbuilder();
    // 通过for循环写入1020个字符
     for (int i=0; i<102; i++)
      sb.append("0123456789");
    // 再写入26个字符。
    sb.append("abcdefghijklmnopqrstuvwxyz");
    // str的总长度是1020+26=1046个字符
    string str = sb.tostring();
    try {
      // 将1046个字符写入到“管道输出流”中
       out.write(str);
       out.close();
     } catch (ioexception e) {
       e.printstacktrace();
     }
   }
 }
 

pipetest.java的代码如下: 

 import java.io.pipedreader;
 import java.io.pipedwriter;
 import java.io.ioexception;
 @suppresswarnings("all")  
 /** 
  * 管道输入流和管道输出流的交互程序
  */  
 public class pipetest {  
   public static void main(string[] args) {  
    sender t1 = new sender();  
   receiver t2 = new receiver();  
    pipedwriter out = t1.getwriter();  
     pipedreader in = t2.getreader();  
     try {  
       //管道连接。下面句话的本质是一样。
       //out.connect(in);  
       in.connect(out);  
       /** 
       * thread类的start方法: 
       * 使该线程开始执行;java 虚拟机调用该线程的 run 方法。  
       * 结果是两个线程并发地运行;当前线程(从调用返回给 start 方法)和另一个线程(执行其 run 方法)。  
       * 多次启动一个线程是非法的。特别是当线程已经结束执行后,不能再重新启动。  
       */
       t.start();
       t.start();
     } catch (ioexception e) {
       e.printstacktrace();
     }
   }
 }

运行结果:

this is a short message

结果说明:

(01) in.connect(out);

        它的作用是将“管道输入流”和“管道输出流”关联起来。查看pipedwriter.java和pipedreader.java中connect()的源码;我们知道 out.connect(in); 等价于 in.connect(out);

(02)

t1.start(); // 启动“sender”线程
t2.start(); // 启动“receiver”线程

先查看sender.java的源码,线程启动后执行run()函数;在sender.java的run()中,调用writeshortmessage();

writeshortmessage();的作用就是向“管道输出流”中写入数据"this is a short message" ;这条数据会被“管道输入流”接收到。下面看看这是如何实现的。

先看write(char char的源码。pipedwriter.java继承于writer.java;writer.java中write(char c[])的源码如下:

public void write(char cbuf[]) throws ioexception {
  write(cbuf, 0, cbuf.length);
}

实际上write(char c[])是调用的pipedwriter.java中的write(char c[], int off, int len)函数。查看write(char c[], int off, int len)的源码,我们发现:它会调用 sink.receive(cbuf, off, len); 进一步查看receive(char c[], int off, int len)的定义,我们知道sink.receive(cbuf, off, len)的作用就是:将“管道输出流”中的数据保存到“管道输入流”的缓冲中。而“管道输入流”的缓冲区buffer的默认大小是1024个字符。

至此,我们知道:t1.start()启动sender线程,而sender线程会将数据"this is a short message"写入到“管道输出流”;而“管道输出流”又会将该数据传输给“管道输入流”,即而保存在“管道输入流”的缓冲中。

接下来,我们看看“用户如何从‘管道输入流'的缓冲中读取数据”。这实际上就是receiver线程的动作。

t2.start() 会启动receiver线程,从而执行receiver.java的run()函数。查看receiver.java的源码,我们知道run()调用了readmessageonce()。

而readmessageonce()就是调用in.read(buf)从“管道输入流in”中读取数据,并保存到buf中。

通过上面的分析,我们已经知道“管道输入流in”的缓冲中的数据是"this is a short message";因此,buf的数据就是"this is a short message"。

为了加深对管道的理解。我们接着进行下面两个小试验。

试验一:修改sender.java

public void run(){  
  writeshortmessage();
  //writelongmessage();
}

修改为

public void run(){  
  //writeshortmessage();
  writelongmessage();
}

运行程序。运行结果如下: 

从中,我们看出,程序运行出错!抛出异常 java.io.ioexception: pipe closed

为什么会这样呢?

我分析一下程序流程。

(01) 在pipetest中,通过in.connect(out)将输入和输出管道连接起来;然后,启动两个线程。t1.start()启动了线程sender,t2.start()启动了线程receiver。

(02) sender线程启动后,通过writelongmessage()写入数据到“输出管道”,out.write(str.tochararray())共写入了1046个字符。而根据pipedwriter的源码,pipedwriter的write()函数会调用pipedreader的receive()函数。而观察pipedreader的receive()函数,我们知道,pipedreader会将接受的数据存储缓冲区。仔细观察receive()函数,有如下代码:

while (in == out) {
  if ((readside != null) && !readside.isalive()) {
    throw new ioexception("pipe broken");
  }
  /* full: kick any waiting readers */
  notifyall();
  try {
    wait(1000);
  } catch (interruptedexception ex) {
    throw new java.io.interruptedioexception();
  }
}

而in和out的初始值分别是in=-1, out=0;结合上面的while(in==out)。我们知道,它的含义就是,每往管道中写入一个字符,就达到了in==out这个条件。然后,就调用notifyall(),唤醒“读取管道的线程”。
也就是,每往管道中写入一个字符,都会阻塞式的等待其它线程读取。

然而,pipedreader的缓冲区的默认大小是1024!但是,此时要写入的数据却有1046!所以,一次性最多只能写入1024个字符。

(03) receiver线程启动后,会调用readmessageonce()读取管道输入流。读取1024个字符会,会调用close()关闭,管道。

由(02)和(03)的分析可知,sender要往管道写入1046个字符。其中,前1024个字符(缓冲区容量是1024)能正常写入,并且每写入一个就读取一个。当写入1025个字符时,依然是依次的调用pipedwriter.java中的write();然后,write()中调用pipedreader.java中的receive();在pipedreader.java中,最终又会调用到receive(int c)函数。 而此时,管道输入流已经被关闭,也就是closedbyreader为true,所以抛出throw new ioexception("pipe closed")。
我们对“试验一”继续进行修改,解决该问题。

试验二: 在“试验一”的基础上继续修改receiver.java

public void run(){  
  readmessageonce() ;
  //readmessagecontinued() ;
}

修改为

public void run(){  
  //readmessageonce() ;
  readmessagecontinued() ;
}

此时,程序能正常运行。运行结果为:

01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
012345678901234567890123456789abcd
efghijklmnopqrstuvwxyz

以上所述是小编给大家介绍的pipedwriter和pipedreader源码分析,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网