管道输入/输出流和普通的文件输入/输出流或者网络输入/输出流不同之处在于,它主要用于线程之间的数据传输,而传输的媒介为内存。
管道输入/输出流主要包括了如下4种具体实现:PipedOutputStream、PipedInputStream、PipedReader和PipedWriter,前两种面向字节,而后两种面向字符。
package gj.concurrent.sync; import java.io.IOException; import java.io.PipedReader; import java.io.PipedWriter; /** * Author: areful */ public class PipedSync { private static class Writer implements Runnable { private PipedWriter out; private Writer(PipedWriter writer) { out = writer; } @Override public void run() { int receive; try { while ((receive = System.in.read()) != -1) { out.write(receive); } } catch (Exception ignored) { } finally { try { out.close(); } catch (IOException ignored) { } } } } private static class Printer implements Runnable { private PipedReader in; private Printer(PipedReader in) { this.in = in; } public void run() { int receive; try { while ((receive = in.read()) != -1) { System.out.print((char) receive); } } catch (IOException ignored) { } } } public static void main(String[] args) throws Exception { PipedWriter out = new PipedWriter(); PipedReader in = new PipedReader(); out.connect(in); Thread printThread = new Thread(new Printer(in), "PrintThread"); printThread.start(); Thread writeThread = new Thread(new Writer(out), "WriteThread"); writeThread.start(); } }