通过管道进行线程间通信:字节流。字符流的用法及API类似
管道流(PipedStream)可以用于不同线程间直接传送数据。
一个线程发送数据到输出管道,另一个线程从输入管道中读取数据。通过使用管道,实现不同线程间的通信,而无须借助于类似临时文件之类的东西。
package thread.communicate; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; /*2015-11-19*/ public class CommunicateWithPipedStream { public static void main(String[] args) { try { PipedOutputStream out = new PipedOutputStream(); DataWriter writer = new DataWriter(out); PipedInputStream in = new PipedInputStream(); DataReader reader = new DataReader(in); // out.connect(in); in.connect(out); new Thread(writer, "Writer").start(); new Thread(reader, "Reader").start(); } catch (Exception e) { e.printStackTrace(); } } } class DataWriter implements Runnable { private PipedOutputStream _out; public DataWriter(PipedOutputStream out) { super(); this._out = out; } @Override public void run() { write(); } public void write() { System.out.println(Thread.currentThread() + "Start write...."); try { for (int i = 0; i < 20; i++) { String outStr = "" + (i + 1); System.out.println(Thread.currentThread() + outStr); _out.write(outStr.getBytes()); } _out.close(); } catch (IOException e) { e.printStackTrace(); } } } class DataReader implements Runnable { private PipedInputStream _in; public DataReader(PipedInputStream in) { _in = in; } @Override public void run() { read(); } public void read() { try { System.out.println(Thread.currentThread() + "Start read...."); byte[] byteArray = new byte[20]; int readLength = _in.read(byteArray); while (readLength != -1) { String newData = new String(byteArray, 0, readLength); System.out.println(Thread.currentThread() + newData); readLength = _in.read(byteArray); } System.out.println(); _in.close(); } catch (Exception e) { e.printStackTrace(); } } }
输出:
Thread[Writer,5,main]Start write.... Thread[Writer,5,main]1 Thread[Reader,5,main]Start read.... Thread[Writer,5,main]2 Thread[Reader,5,main]1 Thread[Reader,5,main]2 Thread[Writer,5,main]3 Thread[Writer,5,main]4 Thread[Writer,5,main]5 Thread[Writer,5,main]6 Thread[Writer,5,main]7 Thread[Writer,5,main]8 Thread[Writer,5,main]9 Thread[Writer,5,main]10 Thread[Writer,5,main]11 Thread[Writer,5,main]12 Thread[Writer,5,main]13 Thread[Writer,5,main]14 Thread[Writer,5,main]15 Thread[Writer,5,main]16 Thread[Writer,5,main]17 Thread[Writer,5,main]18 Thread[Writer,5,main]19 Thread[Writer,5,main]20 Thread[Reader,5,main]34567891011121314151 Thread[Reader,5,main]617181920