java提高篇(23)--PipedWriter、PipedReader简介

来源:互联网 发布:ubuntu lamp环境 编辑:程序博客网 时间:2024/06/16 06:15


             ——管道字符输出流、必须建立在管道输入流之上、所以先介绍管道字符输出流。可以先看示例或者总结、总结写的有点Q、不喜可无视、有误的地方指出则不胜感激。


一:PipedWriter


1、类功能简介:


            管道字符输出流、用于将当前线程的指定字符写入到与此线程对应的管道字符输入流中去、所以PipedReader(pr)、PipedWriter(pw)必须配套使用、缺一不可。管道字符输出流的本质就是调用pr中的方法将字符或者字符数组写入到pr中、这一点是与众不同的地方。所以pw中的方法很少也很简单、主要就是负责将传入的pr与本身绑定、配对使用、然后就是调用绑定的pr的写入方法、将字符或者字符数组写入到pr的缓存字符数组中。


2、PipedWriter  API简介:


      A:关键字


[java] view plain copy
  1. private PipedReader sink;   与此PipedWriter绑定的PipedReader  
  2.   
  3.   
  4. private boolean closed = false;     标示此流是否关闭。  

       B:构造方法


[java] view plain copy
  1. PipedWriter(PipedReader snk)    根据传入的PipedReader构造pw、并将pr与此pw绑定  
  2.      
  3.    PipedWriter()    创建一个pw、在使用之前必须与一个pr绑定  



       C:一般方法


[java] view plain copy
  1. synchronized void connect(PipedReader snk)      将此pw与一个pr绑定  
  2.   
  3. void close()    关闭此流。  
  4.   
  5. synchronized void connect(PipedReader snk)      将此pw与一个pr绑定  
  6.   
  7. synchronized void flush()   flush此流、唤醒pr中所有等待的方法。  
  8.   
  9. void write(int c)   将一个整数写入到与此pw绑定的pr的缓存字符数组buf中去  
  10.   
  11. void write(char cbuf[], int off, int len)   将cbuf的一部分写入pr的buf中去  


3、源码分析


[java] view plain copy
  1. package com.chy.io.original.code;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. public class PipedWriter extends Writer {  
  6.       
  7.     //与此PipedWriter绑定的PipedReader  
  8.     private PipedReader sink;  
  9.   
  10.     //标示此流是否关闭。  
  11.     private boolean closed = false;  
  12.   
  13.     /** 
  14.      * 根据传入的PipedReader构造pw、并将pr与此pw绑定 
  15.      */  
  16.     public PipedWriter(PipedReader snk)  throws IOException {  
  17.         connect(snk);  
  18.     }  
  19.       
  20.     /** 
  21.      * 创建一个pw、在使用之前必须与一个pr绑定 
  22.      */  
  23.     public PipedWriter() {  
  24.     }  
  25.       
  26.     /** 
  27.      * 将此pw与一个pr绑定 
  28.      */  
  29.     public synchronized void connect(PipedReader snk) throws IOException {  
  30.         if (snk == null) {  
  31.             throw new NullPointerException();  
  32.         } else if (sink != null || snk.connected) {  
  33.             throw new IOException("Already connected");  
  34.         } else if (snk.closedByReader || closed) {  
  35.                 throw new IOException("Pipe closed");  
  36.         }  
  37.               
  38.         sink = snk;  
  39.         snk.in = -1;  
  40.         snk.out = 0;  
  41.         snk.connected = true;  
  42.     }  
  43.   
  44.     /** 
  45.      * 将一个整数写入到与此pw绑定的pr的缓存字符数组buf中去 
  46.      */  
  47.     public void write(int c)  throws IOException {  
  48.         if (sink == null) {  
  49.             throw new IOException("Pipe not connected");  
  50.         }  
  51.         sink.receive(c);  
  52.     }  
  53.   
  54.     /** 
  55.      * 将cbuf的一部分写入pr的buf中去 
  56.      */  
  57.     public void write(char cbuf[], int off, int len) throws IOException {  
  58.         if (sink == null) {  
  59.             throw new IOException("Pipe not connected");  
  60.         } else if ((off | len | (off + len) | (cbuf.length - (off + len))) < 0) {  
  61.             throw new IndexOutOfBoundsException();  
  62.         }  
  63.         sink.receive(cbuf, off, len);  
  64.     }  
  65.   
  66.     /** 
  67.      * flush此流、唤醒pr中所有等待的方法。 
  68.      */  
  69.     public synchronized void flush() throws IOException {  
  70.         if (sink != null) {  
  71.                 if (sink.closedByReader || closed) {  
  72.                     throw new IOException("Pipe closed");  
  73.                 }              
  74.                 synchronized (sink) {  
  75.                     sink.notifyAll();  
  76.                 }  
  77.         }  
  78.     }  
  79.   
  80.     /** 
  81.      * 关闭此流。 
  82.      */  
  83.     public void close()  throws IOException {  
  84.         closed = true;  
  85.         if (sink != null) {  
  86.             sink.receivedLast();  
  87.         }  
  88.     }  
  89. }  

4、实例演示:


            因为PipedWriter必须与PipedReader结合使用、所以将两者的示例放在一起。

 

二:PipedReader


1、类功能简介:


            管道字符输入流、用于读取对应绑定的管道字符输出流写入其内置字符缓存数组buffer中的字符、借此来实现线程之间的通信、pr中专门有两个方法供pw调用、receive(char c)、receive(char[] b, int off, intlen)、使得pw可以将字符或者字符数组写入pr的buffer中、

 

2、PipedReader  API简介:


        A:关键字


[java] view plain copy
  1. boolean closedByWriter = false;     标记PipedWriter是否关闭  
  2.   
  3.    boolean closedByReader = false;      标记PipedReader是否关闭  
  4.      
  5.    boolean connected = false;           标记PipedWriter与标记PipedReader是否关闭的连接是否关闭  
  6.   
  7.    Thread readSide;     拥有PipedReader的线程  
  8.      
  9.    Thread writeSide;    拥有PipedWriter的线程  
  10.   
  11.    private static final int DEFAULT_PIPE_SIZE = 1024;       用于循环存放PipedWriter写入的字符数组的默认大小  
  12.   
  13.    char buffer[];       用于循环存放PipedWriter写入的字符数组  
  14.   
  15.    int in = -1; buf中下一个存放PipedWriter调用此PipedReader的receive(int c)时、c在buf中存放的位置的下标。此为初始状态、即buf中没有字符  
  16.   
  17.    int out = 0; buf中下一个被读取的字符的下标  


        B:构造方法


[java] view plain copy
  1. PipedReader(PipedWriter src)    使用默认的buf的大小和传入的pw构造pr  
  2.   
  3. PipedReader(PipedWriter src, int pipeSize)      使用指定的buf的大小和传入的pw构造pr  
  4.   
  5. PipedReader()       使用默认大小构造pr  
  6.   
  7. PipedReader(int pipeSize)       使用指定大小构造pr  


        C:一般方法


[java] view plain copy
  1. void close()    清空buf中数据、关闭此流。  
  2.   
  3. void connect(PipedWriter src)   调用与此流绑定的pw的connect方法、将此流与对应的pw绑定  
  4.   
  5. synchronized boolean ready()    查看此流是否可读  
  6.   
  7. synchronized int read()     从buf中读取一个字符、以整数形式返回  
  8.   
  9. synchronized int read(char cbuf[], int off, int len)    将buf中读取一部分字符到cbuf中。  
  10.   
  11. synchronized void receive(int c)    pw调用此流的此方法、向pr的buf以整数形式中写入一个字符。  
  12.   
  13. synchronized void receive(char c[], int off, int len)   将c中一部分字符写入到buf中。  
  14.   
  15. synchronized void receivedLast()    提醒所有等待的线程、已经接收到了最后一个字符。  


3、源码分析


[java] view plain copy
  1. package com.chy.io.original.code;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. public class PipedReader extends Reader {  
  6.     boolean closedByWriter = false;  
  7.     boolean closedByReader = false;  
  8.     boolean connected = false;  
  9.   
  10.     Thread readSide;  
  11.     Thread writeSide;  
  12.   
  13.    /**  
  14.     * 用于循环存放PipedWriter写入的字符数组的默认大小 
  15.     */   
  16.     private static final int DEFAULT_PIPE_SIZE = 1024;  
  17.   
  18.     /** 
  19.      * 用于循环存放PipedWriter写入的字符数组 
  20.      */  
  21.     char buffer[];  
  22.   
  23.     /** 
  24.      * buf中下一个存放PipedWriter调用此PipedReader的receive(int c)时、c在buf中存放的位置的下标。 
  25.      * in为-1时、说明buf中没有可读取字符、in=out时已经存满了。 
  26.      */  
  27.     int in = -1;  
  28.   
  29.     /** 
  30.      * buf中下一个被读取的字符的下标 
  31.      */  
  32.     int out = 0;  
  33.   
  34.     /** 
  35.      * 使用默认的buf的大小和传入的pw构造pr 
  36.      */  
  37.     public PipedReader(PipedWriter src) throws IOException {  
  38.         this(src, DEFAULT_PIPE_SIZE);  
  39.     }  
  40.   
  41.     /** 
  42.      * 使用指定的buf的大小和传入的pw构造pr 
  43.      */  
  44.     public PipedReader(PipedWriter src, int pipeSize) throws IOException {  
  45.         initPipe(pipeSize);  
  46.         connect(src);  
  47.     }  
  48.   
  49.   
  50.     /** 
  51.      * 使用默认大小构造pr 
  52.      */  
  53.     public PipedReader() {  
  54.         initPipe(DEFAULT_PIPE_SIZE);  
  55.     }  
  56.   
  57.     /** 
  58.      * 使用指定大小构造pr 
  59.      */  
  60.     public PipedReader(int pipeSize) {  
  61.         initPipe(pipeSize);  
  62.     }  
  63.   
  64.     //初始化buf大小  
  65.     private void initPipe(int pipeSize) {  
  66.         if (pipeSize <= 0) {  
  67.             throw new IllegalArgumentException("Pipe size <= 0");  
  68.         }  
  69.         buffer = new char[pipeSize];  
  70.     }  
  71.   
  72.     /** 
  73.      * 调用与此流绑定的pw的connect方法、将此流与对应的pw绑定 
  74.      */  
  75.     public void connect(PipedWriter src) throws IOException {  
  76.         src.connect(this);  
  77.     }  
  78.       
  79.     /** 
  80.      * pw调用此流的此方法、向pr的buf以整数形式中写入一个字符。 
  81.      */  
  82.     synchronized void receive(int c) throws IOException {  
  83.         if (!connected) {  
  84.             throw new IOException("Pipe not connected");  
  85.         } else if (closedByWriter || closedByReader) {  
  86.             throw new IOException("Pipe closed");  
  87.         } else if (readSide != null && !readSide.isAlive()) {  
  88.             throw new IOException("Read end dead");  
  89.         }  
  90.   
  91.         writeSide = Thread.currentThread();  
  92.         while (in == out) {  
  93.             if ((readSide != null) && !readSide.isAlive()) {  
  94.                 throw new IOException("Pipe broken");  
  95.             }  
  96.             //buf中写入的被读取完、唤醒所有此对象监控的线程其他方法、如果一秒钟之后还是满值、则再次唤醒其他方法、直到buf中被读取。  
  97.             notifyAll();      
  98.             try {  
  99.                 wait(1000);  
  100.             } catch (InterruptedException ex) {  
  101.                 throw new java.io.InterruptedIOException();  
  102.             }  
  103.         }  
  104.         //buf中存放第一个字符时、将字符在buf中存放位置的下标in初始化为0、读取的下标也初始化为0、准备接受写入的第一个字符。  
  105.         if (in < 0) {  
  106.             in = 0;  
  107.             out = 0;  
  108.         }  
  109.         buffer[in++] = (char) c;  
  110.         //如果buf中放满了、则再从头开始存放。  
  111.         if (in >= buffer.length) {  
  112.             in = 0;  
  113.         }  
  114.     }  
  115.   
  116.     /** 
  117.      * 将c中一部分字符写入到buf中。 
  118.      */  
  119.     synchronized void receive(char c[], int off, int len)  throws IOException {  
  120.         while (--len >= 0) {  
  121.             receive(c[off++]);  
  122.         }  
  123.     }  
  124.   
  125.     /** 
  126.      * 提醒所有等待的线程、已经接收到了最后一个字符、PipedWriter已关闭。用于PipedWriter的close()方法. 
  127.      */  
  128.     synchronized void receivedLast() {  
  129.         closedByWriter = true;  
  130.         notifyAll();  
  131.     }  
  132.   
  133.     /** 
  134.      * 从buf中读取一个字符、以整数形式返回 
  135.      */  
  136.     public synchronized int read()  throws IOException {  
  137.         if (!connected) {  
  138.             throw new IOException("Pipe not connected");  
  139.         } else if (closedByReader) {  
  140.             throw new IOException("Pipe closed");  
  141.         } else if (writeSide != null && !writeSide.isAlive() && !closedByWriter && (in < 0)) {  
  142.             throw new IOException("Write end dead");  
  143.         }  
  144.   
  145.         readSide = Thread.currentThread();  
  146.         int trials = 2;  
  147.         while (in < 0) {  
  148.             if (closedByWriter) {   
  149.             /* closed by writer, return EOF */  
  150.             return -1;  
  151.             }  
  152.             if ((writeSide != null) && (!writeSide.isAlive()) && (--trials < 0)) {  
  153.             throw new IOException("Pipe broken");  
  154.             }  
  155.                 /* might be a writer waiting */  
  156.             notifyAll();  
  157.             try {  
  158.                 wait(1000);  
  159.             } catch (InterruptedException ex) {  
  160.             throw new java.io.InterruptedIOException();  
  161.             }  
  162.         }  
  163.         int ret = buffer[out++];  
  164.         if (out >= buffer.length) {  
  165.             out = 0;  
  166.         }  
  167.         if (in == out) {  
  168.                 /* now empty */  
  169.             in = -1;          
  170.         }  
  171.         return ret;  
  172.     }  
  173.   
  174.     /** 
  175.      * 将buf中读取一部分字符到cbuf中。 
  176.      */  
  177.     public synchronized int read(char cbuf[], int off, int len)  throws IOException {  
  178.         if (!connected) {  
  179.             throw new IOException("Pipe not connected");  
  180.         } else if (closedByReader) {  
  181.             throw new IOException("Pipe closed");  
  182.         } else if (writeSide != null && !writeSide.isAlive() && !closedByWriter && (in < 0)) {  
  183.             throw new IOException("Write end dead");  
  184.         }  
  185.   
  186.         if ((off < 0) || (off > cbuf.length) || (len < 0) ||  
  187.             ((off + len) > cbuf.length) || ((off + len) < 0)) {  
  188.             throw new IndexOutOfBoundsException();  
  189.         } else if (len == 0) {  
  190.             return 0;  
  191.         }  
  192.   
  193.         /* possibly wait on the first character */  
  194.         int c = read();       
  195.         if (c < 0) {  
  196.             return -1;  
  197.         }  
  198.         cbuf[off] =  (char)c;  
  199.         int rlen = 1;  
  200.         while ((in >= 0) && (--len > 0)) {  
  201.             cbuf[off + rlen] = buffer[out++];  
  202.             rlen++;  
  203.             //如果读取的下一个字符下标大于buffer的size、则重置out、从新开始从第一个开始读取。  
  204.             if (out >= buffer.length) {  
  205.                 out = 0;  
  206.             }  
  207.             //如果下一个写入字符的下标与下一个被读取的下标相同、则清空buf  
  208.             if (in == out) {  
  209.                     /* now empty */  
  210.                 in = -1;      
  211.             }  
  212.         }  
  213.         return rlen;  
  214.     }  
  215.   
  216.     /** 
  217.      * 查看此流是否可读、看各个线程是否关闭、以及buffer中是否有可供读取的字符。 
  218.      */  
  219.     public synchronized boolean ready() throws IOException {  
  220.         if (!connected) {  
  221.             throw new IOException("Pipe not connected");  
  222.         } else if (closedByReader) {  
  223.         throw new IOException("Pipe closed");  
  224.     } else if (writeSide != null && !writeSide.isAlive()  
  225.                    && !closedByWriter && (in < 0)) {  
  226.             throw new IOException("Write end dead");  
  227.         }  
  228.         if (in < 0) {  
  229.             return false;  
  230.         } else {  
  231.             return true;  
  232.         }  
  233.     }  
  234.    
  235.     /** 
  236.      * 清空buf中数据、关闭此流。 
  237.      */  
  238.     public void close()  throws IOException {  
  239.         in = -1;  
  240.         closedByReader = true;  
  241.     }  
  242. }  


4、实例演示:


            用于发送字符的线程:CharSenderThread

[java] view plain copy
  1. package com.chy.io.original.thread;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PipedWriter;  
  5.   
  6. @SuppressWarnings("all")  
  7. public class CharSenderThread implements Runnable {  
  8.     private PipedWriter pw = new PipedWriter();  
  9.       
  10.     public PipedWriter getPipedWriter(){  
  11.         return pw;  
  12.     }  
  13.     @Override  
  14.     public void run() {  
  15.         //sendOneChar();  
  16.         //sendShortMessage();  
  17.         sendLongMessage();  
  18.     }  
  19.   
  20.     private void sendOneChar(){  
  21.         try {  
  22.             pw.write("a".charAt(0));  
  23.             pw.flush();  
  24.             pw.close();  
  25.         } catch (IOException e) {  
  26.             e.printStackTrace();  
  27.         }  
  28.     }  
  29.       
  30.     private void sendShortMessage() {  
  31.         try {  
  32.             pw.write("this is a short message from CharSenderThread !".toCharArray());  
  33.             pw.flush();  
  34.             pw.close();  
  35.         } catch (IOException e) {  
  36.             e.printStackTrace();  
  37.         }  
  38.     }  
  39.       
  40.     private void sendLongMessage(){  
  41.         try {  
  42.             char[] b = new char[1028];  
  43.             //生成一个长度为1028的字符数组、前1020个是1、后8个是2。  
  44.             for(int i=0; i<1020; i++){  
  45.                 b[i] = 'a';  
  46.             }  
  47.             for (int i = 1020; i <1028; i++) {  
  48.                 b[i] = 'b';  
  49.             }  
  50.             pw.write(b);  
  51.             pw.flush();  
  52.             pw.close();  
  53.         } catch (IOException e) {  
  54.             e.printStackTrace();  
  55.         }  
  56.     }  
  57. }  

        用于接收字符的线程: CharReceiveThread

[java] view plain copy
  1. package com.chy.io.original.thread;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PipedReader;  
  5.   
  6. @SuppressWarnings("all")  
  7. public class CharReceiverThread extends Thread {  
  8.       
  9.     private PipedReader pr = new PipedReader();  
  10.       
  11.     public PipedReader getPipedReader(){  
  12.         return pr;  
  13.     }  
  14.     @Override  
  15.     public void run() {  
  16.         //receiveOneChar();  
  17.         //receiveShortMessage();  
  18.         receiverLongMessage();  
  19.     }  
  20.       
  21.     private void receiveOneChar(){  
  22.         try {  
  23.             int n = pr.read();  
  24.             System.out.println(n);  
  25.             pr.close();  
  26.         } catch (IOException e) {  
  27.             e.printStackTrace();  
  28.         }  
  29.     }  
  30.       
  31.     private void receiveShortMessage() {  
  32.         try {  
  33.             char[] b = new char[1024];  
  34.             int n = pr.read(b);  
  35.             System.out.println(new String(b, 0, n));  
  36.             pr.close();  
  37.               
  38.         } catch (IOException e) {  
  39.             e.printStackTrace();  
  40.         }  
  41.     }  
  42.       
  43.     private void receiverLongMessage(){  
  44.         try {  
  45.             char[] b = new char[2048];  
  46.             int count = 0;  
  47.             while(true){  
  48.                 count = pr.read(b);   
  49.                 for (int i = 0; i < count; i++) {  
  50.                     System.out.print(b[i]);  
  51.                 }  
  52.                 if(count == -1)  
  53.                     break;  
  54.             }  
  55.             pr.close();  
  56.               
  57.         } catch (IOException e) {  
  58.             e.printStackTrace();  
  59.         }  
  60.     }  
  61.       
  62. }  

        启动类:PipedWriterAndPipedReaderTest

[java] view plain copy
  1. package com.chy.io.original.test;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PipedReader;  
  5. import java.io.PipedWriter;  
  6.   
  7. import com.chy.io.original.thread.CharReceiverThread;  
  8. import com.chy.io.original.thread.CharSenderThread;  
  9.   
  10. public class PipedWriterAndPipedReaderTest {  
  11.     public static void main(String[] args) throws IOException{  
  12.         CharSenderThread cst = new CharSenderThread();  
  13.         CharReceiverThread crt = new CharReceiverThread();  
  14.         PipedWriter pw = cst.getPipedWriter();  
  15.         PipedReader pr = crt.getPipedReader();  
  16.           
  17.         pw.connect(pr);  
  18.           
  19.         /** 
  20.          * 想想为什么下面这样写会报Piped not connect异常 ? 
  21.          */  
  22.         //new Thread(new CharSenderThread()).start();  
  23.         //new CharReceiverThread().start();  
  24.           
  25.         new Thread(cst).start();  
  26.         crt.start();  
  27.     }  
  28. }  

            两个线程中分别有三个方法、可以对应的每次放开一对方法来测试、还有这里最后一个读取1028个字符的方法用了死循环来读取、可以试试当不用死循环来读取会有什么不一样的效果?初始化字符的时候要用char = 'a' 而不是cahr = "a"、可自己想原因。。。

总结:


           PipedReader、PipedWriter两者的结合如鸳鸯一般、离开哪一方都不能继续存在、同时又如连理枝一般、PipedWriter先通过connect(PipedReader sink)来确定关系、并初始化PipedReader状态、告诉PipedReader只能属于这个PipedWriter、connect =true、当想赠与PipedReader字符时、就直接调用receive(char c) 、receive(char[] b, int off, int len)来将字符或者字符数组放入pr的存折buffer中。站在PipedReader角度上、看上哪个PipedWriter时就暗示pw、将主动权交给pw、调用pw的connect将自己给他去登记。当想要花(将字符读取到程序中)字符了就从buffer中拿、但是自己又没有本事挣字符、所以当buffer中没有字符时、自己就等着、并且跟pw讲没有字符了、pw就会向存折(buffer)中存字符、当然、pw不会一直不断往里存、当存折是空的时候也不会主动存、怕花冒、就等着pr要、要才存。过到最后两个只通过buffer来知道对方的存在与否、每次从buffer中存或者取字符时都会看看对方是否安康、若安好则继续生活、若一方不在、则另一方也不愿独存!


             ——管道字符输出流、必须建立在管道输入流之上、所以先介绍管道字符输出流。可以先看示例或者总结、总结写的有点Q、不喜可无视、有误的地方指出则不胜感激。


一:PipedWriter


1、类功能简介:


            管道字符输出流、用于将当前线程的指定字符写入到与此线程对应的管道字符输入流中去、所以PipedReader(pr)、PipedWriter(pw)必须配套使用、缺一不可。管道字符输出流的本质就是调用pr中的方法将字符或者字符数组写入到pr中、这一点是与众不同的地方。所以pw中的方法很少也很简单、主要就是负责将传入的pr与本身绑定、配对使用、然后就是调用绑定的pr的写入方法、将字符或者字符数组写入到pr的缓存字符数组中。


2、PipedWriter  API简介:


      A:关键字


[java] view plain copy
  1. private PipedReader sink;   与此PipedWriter绑定的PipedReader  
  2.   
  3.   
  4. private boolean closed = false;     标示此流是否关闭。  

       B:构造方法


[java] view plain copy
  1. PipedWriter(PipedReader snk)    根据传入的PipedReader构造pw、并将pr与此pw绑定  
  2.      
  3.    PipedWriter()    创建一个pw、在使用之前必须与一个pr绑定  



       C:一般方法


[java] view plain copy
  1. synchronized void connect(PipedReader snk)      将此pw与一个pr绑定  
  2.   
  3. void close()    关闭此流。  
  4.   
  5. synchronized void connect(PipedReader snk)      将此pw与一个pr绑定  
  6.   
  7. synchronized void flush()   flush此流、唤醒pr中所有等待的方法。  
  8.   
  9. void write(int c)   将一个整数写入到与此pw绑定的pr的缓存字符数组buf中去  
  10.   
  11. void write(char cbuf[], int off, int len)   将cbuf的一部分写入pr的buf中去  


3、源码分析


[java] view plain copy
  1. package com.chy.io.original.code;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. public class PipedWriter extends Writer {  
  6.       
  7.     //与此PipedWriter绑定的PipedReader  
  8.     private PipedReader sink;  
  9.   
  10.     //标示此流是否关闭。  
  11.     private boolean closed = false;  
  12.   
  13.     /** 
  14.      * 根据传入的PipedReader构造pw、并将pr与此pw绑定 
  15.      */  
  16.     public PipedWriter(PipedReader snk)  throws IOException {  
  17.         connect(snk);  
  18.     }  
  19.       
  20.     /** 
  21.      * 创建一个pw、在使用之前必须与一个pr绑定 
  22.      */  
  23.     public PipedWriter() {  
  24.     }  
  25.       
  26.     /** 
  27.      * 将此pw与一个pr绑定 
  28.      */  
  29.     public synchronized void connect(PipedReader snk) throws IOException {  
  30.         if (snk == null) {  
  31.             throw new NullPointerException();  
  32.         } else if (sink != null || snk.connected) {  
  33.             throw new IOException("Already connected");  
  34.         } else if (snk.closedByReader || closed) {  
  35.                 throw new IOException("Pipe closed");  
  36.         }  
  37.               
  38.         sink = snk;  
  39.         snk.in = -1;  
  40.         snk.out = 0;  
  41.         snk.connected = true;  
  42.     }  
  43.   
  44.     /** 
  45.      * 将一个整数写入到与此pw绑定的pr的缓存字符数组buf中去 
  46.      */  
  47.     public void write(int c)  throws IOException {  
  48.         if (sink == null) {  
  49.             throw new IOException("Pipe not connected");  
  50.         }  
  51.         sink.receive(c);  
  52.     }  
  53.   
  54.     /** 
  55.      * 将cbuf的一部分写入pr的buf中去 
  56.      */  
  57.     public void write(char cbuf[], int off, int len) throws IOException {  
  58.         if (sink == null) {  
  59.             throw new IOException("Pipe not connected");  
  60.         } else if ((off | len | (off + len) | (cbuf.length - (off + len))) < 0) {  
  61.             throw new IndexOutOfBoundsException();  
  62.         }  
  63.         sink.receive(cbuf, off, len);  
  64.     }  
  65.   
  66.     /** 
  67.      * flush此流、唤醒pr中所有等待的方法。 
  68.      */  
  69.     public synchronized void flush() throws IOException {  
  70.         if (sink != null) {  
  71.                 if (sink.closedByReader || closed) {  
  72.                     throw new IOException("Pipe closed");  
  73.                 }              
  74.                 synchronized (sink) {  
  75.                     sink.notifyAll();  
  76.                 }  
  77.         }  
  78.     }  
  79.   
  80.     /** 
  81.      * 关闭此流。 
  82.      */  
  83.     public void close()  throws IOException {  
  84.         closed = true;  
  85.         if (sink != null) {  
  86.             sink.receivedLast();  
  87.         }  
  88.     }  
  89. }  

4、实例演示:


            因为PipedWriter必须与PipedReader结合使用、所以将两者的示例放在一起。

 

二:PipedReader


1、类功能简介:


            管道字符输入流、用于读取对应绑定的管道字符输出流写入其内置字符缓存数组buffer中的字符、借此来实现线程之间的通信、pr中专门有两个方法供pw调用、receive(char c)、receive(char[] b, int off, intlen)、使得pw可以将字符或者字符数组写入pr的buffer中、

 

2、PipedReader  API简介:


        A:关键字


[java] view plain copy
  1. boolean closedByWriter = false;     标记PipedWriter是否关闭  
  2.   
  3.    boolean closedByReader = false;      标记PipedReader是否关闭  
  4.      
  5.    boolean connected = false;           标记PipedWriter与标记PipedReader是否关闭的连接是否关闭  
  6.   
  7.    Thread readSide;     拥有PipedReader的线程  
  8.      
  9.    Thread writeSide;    拥有PipedWriter的线程  
  10.   
  11.    private static final int DEFAULT_PIPE_SIZE = 1024;       用于循环存放PipedWriter写入的字符数组的默认大小  
  12.   
  13.    char buffer[];       用于循环存放PipedWriter写入的字符数组  
  14.   
  15.    int in = -1; buf中下一个存放PipedWriter调用此PipedReader的receive(int c)时、c在buf中存放的位置的下标。此为初始状态、即buf中没有字符  
  16.   
  17.    int out = 0; buf中下一个被读取的字符的下标  


        B:构造方法


[java] view plain copy
  1. PipedReader(PipedWriter src)    使用默认的buf的大小和传入的pw构造pr  
  2.   
  3. PipedReader(PipedWriter src, int pipeSize)      使用指定的buf的大小和传入的pw构造pr  
  4.   
  5. PipedReader()       使用默认大小构造pr  
  6.   
  7. PipedReader(int pipeSize)       使用指定大小构造pr  


        C:一般方法


[java] view plain copy
  1. void close()    清空buf中数据、关闭此流。  
  2.   
  3. void connect(PipedWriter src)   调用与此流绑定的pw的connect方法、将此流与对应的pw绑定  
  4.   
  5. synchronized boolean ready()    查看此流是否可读  
  6.   
  7. synchronized int read()     从buf中读取一个字符、以整数形式返回  
  8.   
  9. synchronized int read(char cbuf[], int off, int len)    将buf中读取一部分字符到cbuf中。  
  10.   
  11. synchronized void receive(int c)    pw调用此流的此方法、向pr的buf以整数形式中写入一个字符。  
  12.   
  13. synchronized void receive(char c[], int off, int len)   将c中一部分字符写入到buf中。  
  14.   
  15. synchronized void receivedLast()    提醒所有等待的线程、已经接收到了最后一个字符。  


3、源码分析


[java] view plain copy
  1. package com.chy.io.original.code;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. public class PipedReader extends Reader {  
  6.     boolean closedByWriter = false;  
  7.     boolean closedByReader = false;  
  8.     boolean connected = false;  
  9.   
  10.     Thread readSide;  
  11.     Thread writeSide;  
  12.   
  13.    /**  
  14.     * 用于循环存放PipedWriter写入的字符数组的默认大小 
  15.     */   
  16.     private static final int DEFAULT_PIPE_SIZE = 1024;  
  17.   
  18.     /** 
  19.      * 用于循环存放PipedWriter写入的字符数组 
  20.      */  
  21.     char buffer[];  
  22.   
  23.     /** 
  24.      * buf中下一个存放PipedWriter调用此PipedReader的receive(int c)时、c在buf中存放的位置的下标。 
  25.      * in为-1时、说明buf中没有可读取字符、in=out时已经存满了。 
  26.      */  
  27.     int in = -1;  
  28.   
  29.     /** 
  30.      * buf中下一个被读取的字符的下标 
  31.      */  
  32.     int out = 0;  
  33.   
  34.     /** 
  35.      * 使用默认的buf的大小和传入的pw构造pr 
  36.      */  
  37.     public PipedReader(PipedWriter src) throws IOException {  
  38.         this(src, DEFAULT_PIPE_SIZE);  
  39.     }  
  40.   
  41.     /** 
  42.      * 使用指定的buf的大小和传入的pw构造pr 
  43.      */  
  44.     public PipedReader(PipedWriter src, int pipeSize) throws IOException {  
  45.         initPipe(pipeSize);  
  46.         connect(src);  
  47.     }  
  48.   
  49.   
  50.     /** 
  51.      * 使用默认大小构造pr 
  52.      */  
  53.     public PipedReader() {  
  54.         initPipe(DEFAULT_PIPE_SIZE);  
  55.     }  
  56.   
  57.     /** 
  58.      * 使用指定大小构造pr 
  59.      */  
  60.     public PipedReader(int pipeSize) {  
  61.         initPipe(pipeSize);  
  62.     }  
  63.   
  64.     //初始化buf大小  
  65.     private void initPipe(int pipeSize) {  
  66.         if (pipeSize <= 0) {  
  67.             throw new IllegalArgumentException("Pipe size <= 0");  
  68.         }  
  69.         buffer = new char[pipeSize];  
  70.     }  
  71.   
  72.     /** 
  73.      * 调用与此流绑定的pw的connect方法、将此流与对应的pw绑定 
  74.      */  
  75.     public void connect(PipedWriter src) throws IOException {  
  76.         src.connect(this);  
  77.     }  
  78.       
  79.     /** 
  80.      * pw调用此流的此方法、向pr的buf以整数形式中写入一个字符。 
  81.      */  
  82.     synchronized void receive(int c) throws IOException {  
  83.         if (!connected) {  
  84.             throw new IOException("Pipe not connected");  
  85.         } else if (closedByWriter || closedByReader) {  
  86.             throw new IOException("Pipe closed");  
  87.         } else if (readSide != null && !readSide.isAlive()) {  
  88.             throw new IOException("Read end dead");  
  89.         }  
  90.   
  91.         writeSide = Thread.currentThread();  
  92.         while (in == out) {  
  93.             if ((readSide != null) && !readSide.isAlive()) {  
  94.                 throw new IOException("Pipe broken");  
  95.             }  
  96.             //buf中写入的被读取完、唤醒所有此对象监控的线程其他方法、如果一秒钟之后还是满值、则再次唤醒其他方法、直到buf中被读取。  
  97.             notifyAll();      
  98.             try {  
  99.                 wait(1000);  
  100.             } catch (InterruptedException ex) {  
  101.                 throw new java.io.InterruptedIOException();  
  102.             }  
  103.         }  
  104.         //buf中存放第一个字符时、将字符在buf中存放位置的下标in初始化为0、读取的下标也初始化为0、准备接受写入的第一个字符。  
  105.         if (in < 0) {  
  106.             in = 0;  
  107.             out = 0;  
  108.         }  
  109.         buffer[in++] = (char) c;  
  110.         //如果buf中放满了、则再从头开始存放。  
  111.         if (in >= buffer.length) {  
  112.             in = 0;  
  113.         }  
  114.     }  
  115.   
  116.     /** 
  117.      * 将c中一部分字符写入到buf中。 
  118.      */  
  119.     synchronized void receive(char c[], int off, int len)  throws IOException {  
  120.         while (--len >= 0) {  
  121.             receive(c[off++]);  
  122.         }  
  123.     }  
  124.   
  125.     /** 
  126.      * 提醒所有等待的线程、已经接收到了最后一个字符、PipedWriter已关闭。用于PipedWriter的close()方法. 
  127.      */  
  128.     synchronized void receivedLast() {  
  129.         closedByWriter = true;  
  130.         notifyAll();  
  131.     }  
  132.   
  133.     /** 
  134.      * 从buf中读取一个字符、以整数形式返回 
  135.      */  
  136.     public synchronized int read()  throws IOException {  
  137.         if (!connected) {  
  138.             throw new IOException("Pipe not connected");  
  139.         } else if (closedByReader) {  
  140.             throw new IOException("Pipe closed");  
  141.         } else if (writeSide != null && !writeSide.isAlive() && !closedByWriter && (in < 0)) {  
  142.             throw new IOException("Write end dead");  
  143.         }  
  144.   
  145.         readSide = Thread.currentThread();  
  146.         int trials = 2;  
  147.         while (in < 0) {  
  148.             if (closedByWriter) {   
  149.             /* closed by writer, return EOF */  
  150.             return -1;  
  151.             }  
  152.             if ((writeSide != null) && (!writeSide.isAlive()) && (--trials < 0)) {  
  153.             throw new IOException("Pipe broken");  
  154.             }  
  155.                 /* might be a writer waiting */  
  156.             notifyAll();  
  157.             try {  
  158.                 wait(1000);  
  159.             } catch (InterruptedException ex) {  
  160.             throw new java.io.InterruptedIOException();  
  161.             }  
  162.         }  
  163.         int ret = buffer[out++];  
  164.         if (out >= buffer.length) {  
  165.             out = 0;  
  166.         }  
  167.         if (in == out) {  
  168.                 /* now empty */  
  169.             in = -1;          
  170.         }  
  171.         return ret;  
  172.     }  
  173.   
  174.     /** 
  175.      * 将buf中读取一部分字符到cbuf中。 
  176.      */  
  177.     public synchronized int read(char cbuf[], int off, int len)  throws IOException {  
  178.         if (!connected) {  
  179.             throw new IOException("Pipe not connected");  
  180.         } else if (closedByReader) {  
  181.             throw new IOException("Pipe closed");  
  182.         } else if (writeSide != null && !writeSide.isAlive() && !closedByWriter && (in < 0)) {  
  183.             throw new IOException("Write end dead");  
  184.         }  
  185.   
  186.         if ((off < 0) || (off > cbuf.length) || (len < 0) ||  
  187.             ((off + len) > cbuf.length) || ((off + len) < 0)) {  
  188.             throw new IndexOutOfBoundsException();  
  189.         } else if (len == 0) {  
  190.             return 0;  
  191.         }  
  192.   
  193.         /* possibly wait on the first character */  
  194.         int c = read();       
  195.         if (c < 0) {  
  196.             return -1;  
  197.         }  
  198.         cbuf[off] =  (char)c;  
  199.         int rlen = 1;  
  200.         while ((in >= 0) && (--len > 0)) {  
  201.             cbuf[off + rlen] = buffer[out++];  
  202.             rlen++;  
  203.             //如果读取的下一个字符下标大于buffer的size、则重置out、从新开始从第一个开始读取。  
  204.             if (out >= buffer.length) {  
  205.                 out = 0;  
  206.             }  
  207.             //如果下一个写入字符的下标与下一个被读取的下标相同、则清空buf  
  208.             if (in == out) {  
  209.                     /* now empty */  
  210.                 in = -1;      
  211.             }  
  212.         }  
  213.         return rlen;  
  214.     }  
  215.   
  216.     /** 
  217.      * 查看此流是否可读、看各个线程是否关闭、以及buffer中是否有可供读取的字符。 
  218.      */  
  219.     public synchronized boolean ready() throws IOException {  
  220.         if (!connected) {  
  221.             throw new IOException("Pipe not connected");  
  222.         } else if (closedByReader) {  
  223.         throw new IOException("Pipe closed");  
  224.     } else if (writeSide != null && !writeSide.isAlive()  
  225.                    && !closedByWriter && (in < 0)) {  
  226.             throw new IOException("Write end dead");  
  227.         }  
  228.         if (in < 0) {  
  229.             return false;  
  230.         } else {  
  231.             return true;  
  232.         }  
  233.     }  
  234.    
  235.     /** 
  236.      * 清空buf中数据、关闭此流。 
  237.      */  
  238.     public void close()  throws IOException {  
  239.         in = -1;  
  240.         closedByReader = true;  
  241.     }  
  242. }  


4、实例演示:


            用于发送字符的线程:CharSenderThread

[java] view plain copy
  1. package com.chy.io.original.thread;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PipedWriter;  
  5.   
  6. @SuppressWarnings("all")  
  7. public class CharSenderThread implements Runnable {  
  8.     private PipedWriter pw = new PipedWriter();  
  9.       
  10.     public PipedWriter getPipedWriter(){  
  11.         return pw;  
  12.     }  
  13.     @Override  
  14.     public void run() {  
  15.         //sendOneChar();  
  16.         //sendShortMessage();  
  17.         sendLongMessage();  
  18.     }  
  19.   
  20.     private void sendOneChar(){  
  21.         try {  
  22.             pw.write("a".charAt(0));  
  23.             pw.flush();  
  24.             pw.close();  
  25.         } catch (IOException e) {  
  26.             e.printStackTrace();  
  27.         }  
  28.     }  
  29.       
  30.     private void sendShortMessage() {  
  31.         try {  
  32.             pw.write("this is a short message from CharSenderThread !".toCharArray());  
  33.             pw.flush();  
  34.             pw.close();  
  35.         } catch (IOException e) {  
  36.             e.printStackTrace();  
  37.         }  
  38.     }  
  39.       
  40.     private void sendLongMessage(){  
  41.         try {  
  42.             char[] b = new char[1028];  
  43.             //生成一个长度为1028的字符数组、前1020个是1、后8个是2。  
  44.             for(int i=0; i<1020; i++){  
  45.                 b[i] = 'a';  
  46.             }  
  47.             for (int i = 1020; i <1028; i++) {  
  48.                 b[i] = 'b';  
  49.             }  
  50.             pw.write(b);  
  51.             pw.flush();  
  52.             pw.close();  
  53.         } catch (IOException e) {  
  54.             e.printStackTrace();  
  55.         }  
  56.     }  
  57. }  

        用于接收字符的线程: CharReceiveThread

[java] view plain copy
  1. package com.chy.io.original.thread;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PipedReader;  
  5.   
  6. @SuppressWarnings("all")  
  7. public class CharReceiverThread extends Thread {  
  8.       
  9.     private PipedReader pr = new PipedReader();  
  10.       
  11.     public PipedReader getPipedReader(){  
  12.         return pr;  
  13.     }  
  14.     @Override  
  15.     public void run() {  
  16.         //receiveOneChar();  
  17.         //receiveShortMessage();  
  18.         receiverLongMessage();  
  19.     }  
  20.       
  21.     private void receiveOneChar(){  
  22.         try {  
  23.             int n = pr.read();  
  24.             System.out.println(n);  
  25.             pr.close();  
  26.         } catch (IOException e) {  
  27.             e.printStackTrace();  
  28.         }  
  29.     }  
  30.       
  31.     private void receiveShortMessage() {  
  32.         try {  
  33.             char[] b = new char[1024];  
  34.             int n = pr.read(b);  
  35.             System.out.println(new String(b, 0, n));  
  36.             pr.close();  
  37.               
  38.         } catch (IOException e) {  
  39.             e.printStackTrace();  
  40.         }  
  41.     }  
  42.       
  43.     private void receiverLongMessage(){  
  44.         try {  
  45.             char[] b = new char[2048];  
  46.             int count = 0;  
  47.             while(true){  
  48.                 count = pr.read(b);   
  49.                 for (int i = 0; i < count; i++) {  
  50.                     System.out.print(b[i]);  
  51.                 }  
  52.                 if(count == -1)  
  53.                     break;  
  54.             }  
  55.             pr.close();  
  56.               
  57.         } catch (IOException e) {  
  58.             e.printStackTrace();  
  59.         }  
  60.     }  
  61.       
  62. }  

        启动类:PipedWriterAndPipedReaderTest

[java] view plain copy
  1. package com.chy.io.original.test;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PipedReader;  
  5. import java.io.PipedWriter;  
  6.   
  7. import com.chy.io.original.thread.CharReceiverThread;  
  8. import com.chy.io.original.thread.CharSenderThread;  
  9.   
  10. public class PipedWriterAndPipedReaderTest {  
  11.     public static void main(String[] args) throws IOException{  
  12.         CharSenderThread cst = new CharSenderThread();  
  13.         CharReceiverThread crt = new CharReceiverThread();  
  14.         PipedWriter pw = cst.getPipedWriter();  
  15.         PipedReader pr = crt.getPipedReader();  
  16.           
  17.         pw.connect(pr);  
  18.           
  19.         /** 
  20.          * 想想为什么下面这样写会报Piped not connect异常 ? 
  21.          */  
  22.         //new Thread(new CharSenderThread()).start();  
  23.         //new CharReceiverThread().start();  
  24.           
  25.         new Thread(cst).start();  
  26.         crt.start();  
  27.     }  
  28. }  

            两个线程中分别有三个方法、可以对应的每次放开一对方法来测试、还有这里最后一个读取1028个字符的方法用了死循环来读取、可以试试当不用死循环来读取会有什么不一样的效果?初始化字符的时候要用char = 'a' 而不是cahr = "a"、可自己想原因。。。

总结:


           PipedReader、PipedWriter两者的结合如鸳鸯一般、离开哪一方都不能继续存在、同时又如连理枝一般、PipedWriter先通过connect(PipedReader sink)来确定关系、并初始化PipedReader状态、告诉PipedReader只能属于这个PipedWriter、connect =true、当想赠与PipedReader字符时、就直接调用receive(char c) 、receive(char[] b, int off, int len)来将字符或者字符数组放入pr的存折buffer中。站在PipedReader角度上、看上哪个PipedWriter时就暗示pw、将主动权交给pw、调用pw的connect将自己给他去登记。当想要花(将字符读取到程序中)字符了就从buffer中拿、但是自己又没有本事挣字符、所以当buffer中没有字符时、自己就等着、并且跟pw讲没有字符了、pw就会向存折(buffer)中存字符、当然、pw不会一直不断往里存、当存折是空的时候也不会主动存、怕花冒、就等着pr要、要才存。过到最后两个只通过buffer来知道对方的存在与否、每次从buffer中存或者取字符时都会看看对方是否安康、若安好则继续生活、若一方不在、则另一方也不愿独存!


原创粉丝点击