利用PipedInputStream和PipedOutputStream实现线程间通信

问题描述

多个线程之间可以通过管道流实现数据的传输,利用管道输入流(PipedInputStream)和管道输出流(PipedOutputStream)创建两个线程,一个线程从文件中读取数据,从管道输出流输出,另一个线程从管道输入流中取出文件据,并保存到本地自己任意指定的文件中。实现文件的传输功能。

设计思路

  • 创建管道输入流和输出流对象,并将其连接;
  • 创建线程一,将本地文件读取到管道输出流中;
  • 创建线程二,在管道输入流中接收文件到本地。

完整源代码

package PipeStream;
import java.io.*;

public class Main {
    public static void main(String[] args)throws Exception{
        final PipedInputStream pis = new PipedInputStream();
        final PipedOutputStream pos = new PipedOutputStream();
        pos.connect(pis);

        //文件读取线程
        new Thread(()->{
            try{
                File file = new File("D:\\File\\Others\\source\\monkey.txt");
                FileInputStream in = new FileInputStream(file);
                int b;
                while(true){
                    b=in.read();
                    pos.write(b);
                    if(b==-1)   break;
                }
                System.out.println("文件输入成功");
                pos.close();
                in.close();
            }catch(Exception e){System.out.println("错误信息为:"+e.getMessage());}
        }).start();

        //文件输出线程
        new Thread(()->{
            try{
                File file = new File("D:\\File\\Others\\target\\monkey.txt");
                OutputStream out = new FileOutputStream(file);
                int len;
                while((len=pis.read())!=-1) out.write(len);
                System.out.println("文件输出成功");
                pis.close();
                out.close();
            }catch(Exception e){System.out.println("错误信息为:"+e.getMessage());}
        }).start();
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值