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();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章