• 管道流


    管道流主要可以进行两个线程之间的通信。

    
    PipedOutputStream 管道输出流
    
    PipedInputStream 管道输入流
    

    【例子1】验证管道流

    
    /**
    
     * 验证管道流
    
     * */
    
    import java.io.*;
    
    
    
    /**
    
     * 消息发送类
    
     * */
    
    class Send implements Runnable{
    
        private PipedOutputStream out=null;
    
        public Send() {
    
            out=new PipedOutputStream();
    
        }
    
        public PipedOutputStream getOut(){
    
            return this.out;
    
        }
    
        public void run(){
    
            String message="hello , Rollen";
    
            try{
    
                out.write(message.getBytes());
    
            }catch (Exception e) {
    
                e.printStackTrace();
    
            }try{
    
                out.close();
    
            }catch (Exception e) {
    
                e.printStackTrace();
    
            }
    
        }
    
    }
    
    
    
    /**
    
     * 接受消息类
    
     * */
    
    class Recive implements Runnable{
    
        private PipedInputStream input=null;
    
        public Recive(){
    
            this.input=new PipedInputStream();
    
        }
    
        public PipedInputStream getInput(){
    
            return this.input;
    
        }
    
        public void run(){
    
            byte[] b=new byte[1000];
    
            int len=0;
    
            try{
    
                len=this.input.read(b);
    
            }catch (Exception e) {
    
                e.printStackTrace();
    
            }try{
    
                input.close();
    
            }catch (Exception e) {
    
                e.printStackTrace();
    
            }
    
            System.out.println("接受的内容为 "+(new String(b,0,len)));
    
        }
    
    }
    
    /**
    
     * 测试类
    
     * */
    
    class hello{
    
        public static void main(String[] args) throws IOException {
    
            Send send=new Send();
    
            Recive recive=new Recive();
    
            try{
    
    //管道连接
    
                send.getOut().connect(recive.getInput());
    
            }catch (Exception e) {
    
                e.printStackTrace();
    
            }
    
            new Thread(send).start();
    
            new Thread(recive).start();
    
        }
    
    }
    

    【运行结果】:接受的内容为 hello , Rollen

  • 相关阅读:
    google说 老子 = I !
    昨日种种死 今日种种生
    设定Access数据库自增长字段初始值
    [c路历程]品品数组这杯茶
    爱上位运算
    .Net中的委托
    Jquery css函数用法(判断标签是否拥有某属性)
    记录几条简单的正则表达式
    ASP.NET MVC中DropDownList的使用
    C#如何获取object对象的属性值
  • 原文地址:https://www.cnblogs.com/yuyu666/p/9733903.html
Copyright © 2020-2023  润新知