Fork me on GitHub

java拓展----管道流

目录

    1.介绍管道流

  2.管道流的基本实现

  3.管道流的使用场景及注意事项

 

一、介绍管道流

  

  管道流的主要作用是可以进行两个线程间的通讯,分为管道输出流(PipedOutputStream)、管道输入流(PipedInputStream),如果要想进行管道输出,则必须把输出流连在输入流之上。

  管道流的模型如下:

  

  利用管道流的这一特性我们可以在线程之间传递文件。

 

二、管道流的基本实现

 

  管道流可以比作是一根管道,我们可以将输入和输出的管道相连,达到线程之间传递数据的目的。

  以下是管道流的基本实现:

  接收数据线程:

package io;


import java.io.IOException;
import java.io.PipedInputStream;

/**
 * 接收线程
 */
public class Recevie implements Runnable{
    //管输入道流
    private PipedInputStream pis = null;
    //构造方法
    public Recevie() {
        this.pis = new PipedInputStream();
    }

    @Override
    public void run() {
        //缓冲区
        byte [] b = new byte[1024];
        int len = 0;
        try {
            //将数据读取到b中
            len = pis.read(b);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                pis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("接收到的内容为:"+new String(b,0,len));
    }

    public PipedInputStream getPis() {
        return pis;
    }
}

  发送数据线程:

package io;

import java.io.IOException;
import java.io.PipedOutputStream;

/**
 * 发送线程
 */
public class Send implements Runnable{
    //管道输出流
    private PipedOutputStream pos = null;

    public Send() {
        this.pos = new PipedOutputStream();
    }

    @Override
    public void run() {
        String str = "hello piped";
        try {
            pos.write(str.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                pos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public PipedOutputStream getPos() {
        return pos;
    }
}

  链接管道并启动线程:

package io;

import java.io.IOException;

/**
 * 管道连接类
 */
public class Pip {
    public static void main(String[] args) {
        Send send = new Send();
        Recevie recevie = new Recevie();
        try {
            send.getPos().connect(recevie.getPis());
        } catch (IOException e) {
            e.printStackTrace();
        }
        new Thread(send).start();
        new Thread(recevie).start();
    }
}

  

三、管道流的使用场景及注意事项

  在java API文档中的解释是这样的:

  官方说明不建议使用单个线程,可能会死锁。所以在实际开发过程中要注意尽量不要写在单个线程中。

  另外在jdk1.1中还出现了另外两个管道流:PipedReaderPipedWriter

  这两个流是用来传递字符的。在使用范围上只能传递文本文件。不能用来传递多媒体文件。

posted @ 2018-12-08 15:28  Banana_Fish  阅读(495)  评论(0编辑  收藏  举报