java 编程学习之管道

管道的理解

java管道与unix/Linux的管道是不同的,在Unix/Linux中,在不同地址空间运行的两个进程可以通过管道通信。在Java中,通信的双方应该是运行在同一进程中的不同线程。Java IO中的管道为运行在同一个JVM中的两个线程提供了通信的能力。所以管道也可以作为数据源以及目标媒介。–Jakob Jenkov 译者: 李璟

管道主要的作用是用于两个线程通信,分为管道输入流(PipedInputStream)和管道输出流(PipedOutputStream),必须通过connect将输入流和输出流链接起来。

例子

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

public class PipeExample {
    private static PipeExample ourInstance = new PipeExample();

    public static PipeExample getInstance() {
        return ourInstance;
    }

    private PipeExample() {
    }
    public static void main(String [] args) throws IOException {
        final PipedOutputStream outputStream = new PipedOutputStream();
        final PipedInputStream inputStream = new PipedInputStream();
//        inputStream.connect(outputStream);
        outputStream.connect(inputStream);
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    outputStream.write("Hello world,pipe!".getBytes());
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    int data = inputStream.read();
                    while (data != -1){
                        System.out.print((char)data);
                        data = inputStream.read();
                    }
                }catch (IOException e) {
                }
            }
        });
        thread1.start();
        thread2.start();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章