IO之 管道流

管道流:

实现两个线程之间的数据交互. PipedInputStream PipedOutputStream PipedReder
PipedWriter

中文API解释:
PipedInputStream

public class PipedInputStreamextends InputStream管道输入流应该连接到管道输出流;管道输入流提供要写入管道输出流的所有数据字节。通常,数据由某个线程从 PipedInputStream 对象读取,并由其他线程将其写入到相应的 PipedOutputStream。不建议对这两个对象尝试使用单个线程,因为这样可能死锁线程。管道输入流包含一个缓冲区,可在缓冲区限定的范围内将读操作和写操作分离开。如果向连接管道输出流提供数据字节的线程不再存在,则认为该管道已损坏。

PipedOutputStream

public class PipedOutputStreamextends OutputStream可以将管道输出流连接到管道输入流来创建通信管道。管道输出流是管道的发送端。通常,数据由某个线程写入 PipedOutputStream 对象,并由其他线程从连接的 PipedInputStream 读取。不建议对这两个对象尝试使用单个线程,因为这样可能会造成该线程死锁。如果某个线程正从连接的管道输入流中读取数据字节,但该线程不再处于活动状态,则该管道被视为处于 毁坏 状态。


练习代码:
这里写图片描述
这里写图片描述
这里写图片描述

    class AThread extends Thread{
        private PipedOutputStream out = new PipedOutputStream();
        public PipedOutputStream getOut(){
            return this.out;
        }
        @Override
        public void run() {
                try {
                    for(int i = 65 ;i < 65 + 26; i++){
                        out.write(i);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

    class BThread extends Thread{
        private PipedInputStream in = null;
        public BThread(AThread aThread) throws Exception{
            in = new PipedInputStream(aThread.getOut());
        }
        @Override
        public void run() {
            int len = -1;
            try {
                while ((len = in.read()) != -1){
                    System.out.println((char)len);
                }
                in.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    @Test
    public void t() throws Exception {
        AThread aThread = new AThread();
        BThread bThread = new BThread(aThread);
        aThread.start();
        bThread.start();
    }

输出(结果每次运行都不相同):
A
B
C
D
E
F
G
H
I

J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值