java中PipedOutputStream和PipedInputStream类用法



大概就是这么个意思:两个线程需要通信,就是传写数据啊什么的给另外一个线程,PipleOutputString负责输出数据,  outStream.write(info.getBytes());(貌似必须是byte的,这才符合计算机内存的最原始的规则),PipleInputStrieam负责输入,两者都是在程序中进行的,这一点与FileInputStream不同,它读取传递进入管道的数据,  int len = inStream.read(buf);,PipleOutPutStream写的对象是想要传递的数据,需要先将其转换成byte类型的格式,接收处需要byte类型的but接受数据

import java.io.*;


  1. public class PipedStreamTest {
        public static void main(String [] args) {
            Sender sender = new Sender();
            Receiver receiver = new Receiver();
            
            PipedOutputStream outStream = sender.getOutStream();
            PipedInputStream inStream = receiver.getInStream();
            
            try {
                //inStream.connect(outStream); // 与下一句一样
                outStream.connect(inStream);
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            sender.start();
            receiver.start();
        }
    }

    class Sender extends Thread {
        private PipedOutputStream outStream = new PipedOutputStream();
        
        public PipedOutputStream getOutStream() {
            return outStream;
        }
        
        public void run() {
            String info = "hello, receiver";
            
            try {
                outStream.write(info.getBytes());
                
                outStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    class Receiver extends Thread {
        private PipedInputStream inStream = new PipedInputStream();
        
        public PipedInputStream getInStream() {
            return inStream;
        }
        
        public void run() {
            byte[] buf = new byte[1024];
            
            try {
                int len = inStream.read(buf);
                
                System.out.println("receive message from sender : " + new String(buf, 0, len));
                
                inStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }    
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值