管道流----基于线程通信

    技术2025-08-23  9

    管道流----基于线程通信

    文章目录

    管道流----基于线程通信前言案例演示运行结果总结

    前言

    管道流的主要作用是进行线程之间的通信。要实现线程通信,需要用到PipedInputStream、PipedOutputStream管道输入流和管道输出流两个类,它们都是字节流操作类,为InputStream和OutputStream的子类。

    通过PipedOutputStream类的connect(PipedInputStream snk)进行两个线程通信类的连接,参数为线程通信接受类的管道输入流实例。

    案例演示

    package chapter_twelve; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; //定义一个线程操作类,用于在线程通信中发送信息 class Send implements Runnable{ private PipedOutputStream pipedOutputStream; //定义管道输出流对象 public Send() { this.pipedOutputStream = new PipedOutputStream(); //通过构造方法实例化管道输出流对象 } @Override public void run() { String string = "Hello World!!!"; //定义管道输出数据要输出的信息 byte[] bytes = string.getBytes(); //将信息转化为byte字节以字节输出流的方式输出 try { this.pipedOutputStream.write(bytes); //管道输出流输出信息 this.pipedOutputStream.close(); //关闭管道输出流 } catch (IOException e) { //异常处理 e.printStackTrace(); } } public PipedOutputStream getPipedOutputStream() { //获取本类管道输出流的对象 return pipedOutputStream; } } //定义线程类,用于线程通信接收信息的类 class Receive implements Runnable{ private PipedInputStream pipedInputStream; //定义管道字节输入流,用于接收管道通信之间的数据 public Receive() { //通过构造方法实例化对象 this.pipedInputStream = new PipedInputStream(); } @Override public void run() { byte[] bytes = new byte[1024]; //声明byte数组 try { int len = this.pipedInputStream.read(bytes); //将读取到管道输出流中内容读到byte数组中 this.pipedInputStream.close(); //关闭管道字节输入流 System.out.println(new String(bytes,0,len)); //输出读取出的数据 } catch (IOException e) { //异常处理 e.printStackTrace(); } } public PipedInputStream getPipedInputStream() { //返回管道字节输入流 return pipedInputStream; } } public class PipedDemo { public static void main(String[] args) throws Exception{ Send send = new Send(); //实例化线程通信的信息发送类 Receive receive = new Receive(); //实例化线程通信的信息接受类 send.getPipedOutputStream().connect(receive.getPipedInputStream()); //对这两个类的管道流进行连接 new Thread(send).start(); //启动线程 new Thread(receive).start(); //若接收类线程先执行,无数据读入时,会等待管道输出流的数据输接收后才能继续执行 } }

    运行结果

    Hello World!!!

    总结

    管道流在线程通信之间的应用比较广泛,也是对字节流操作的类。需要注意的是,若线程接受类未接收到管道输出流的传送数据,会等待管道输出流输出数据,所以小伙伴们不必担心 接受类先执行的问题,哈哈,这也是我之前的疑虑,如果有看法不同的大神,欢迎指教,共同进步!!!

    Processed: 0.017, SQL: 9