PipedWriter PipedReader 源码分析

转自:http://www.fengfly.com/plus/view-214070-1.html

PipedWriter 是字符管道输出流,它继承于Writer。
PipedReader 是字符管道输入流,它继承于Writer。
PipedWriter和PipedReader的作用是可以通过管道进行线程间的通讯。在使用管道通信时,必须将PipedWriter和PipedReader配套使用。

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))) < 0) {  
            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();  
        }  
    }  
} 

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 = -1;  
    //下一个读取字符的位置。in==out代表满,说明“写入的数据”全部被读取了。  
    int out = 0;  
 
    // 构造函数:指定与“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 >= 0) {  
            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 < 0)) {  
            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 < 0)) {  
                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 = -1;  
            }  
        }  
        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 < 0)) {  
            throw new IOException("Write end dead");  
        }  
        if (in < 0) {  
            return false;  
        } else {  
            return true;  
        }  
    }  
    // 关闭PipedReader  
    public void close()  throws IOException {  
        in = -1;  
        closedByReader = true;  
    }  
} 


示例见原文




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【优质项目推荐】 1、项目代码均经过严格本地测试,运行OK,确保功能稳定后才上传平台。可放心下载并立即投入使用,若遇到任何使用问题,随时欢迎私信反馈与沟通,博主会第一时间回复。 2、项目适用于计算机相关专业(如计科、信息安全、数据科学、人工智能、通信、物联网、自动化、电子信息等)的在校学生、专业教师,或企业员工,小白入门等都适用。 3、该项目不仅具有很高的学习借鉴价值,对于初学者来说,也是入门进阶的绝佳选择;当然也可以直接用于 毕设、课设、期末大作业或项目初期立项演示等。 3、开放创新:如果您有一定基础,且热爱探索钻研,可以在此代码基础上二次开发,进行修改、扩展,创造出属于自己的独特应用。 欢迎下载使用优质资!欢迎借鉴使用,并欢迎学习交流,共同探索编程的无穷魅力! 基于业务逻辑生成特征变量python实现码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现码+数据集+超详细注释.zip

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值