一个线程发送数据到输出管道,另一个线程从输入管道中读取数据。通过使用管道,实现不同线程间的通信,而无须借助于类似临时文件之类的东西。
在java的jdk中提供了4个类来使线程间可以进行通信: PipedInputStream 和 PipedOutputStream PipedReader 和 PipedWriterpublic static class ReadClient implements Runnable{ private PipedInputStream reader; public ReadClient(PipedInputStream reader) { this.reader = reader; } @Override public void run() { byte[] bytes = new byte[50]; try { do { int readLength = reader.read(bytes);//方法会一直阻塞,直到有数据被写入 if(readLength==-1){continue;} String message = new String(bytes,0,readLength); System.out.println("get: "+message); }while(true); } catch (IOException e) { //something }finally{ try { reader.close(); } catch (IOException e) { //something } } }}public static class WriteClient implements Runnable{ private PipedOutputStream writer; public WriteClient(PipedOutputStream writer) { this.writer = writer; } @Override public void run() { int seed = 0; try { while (true) { seed++; String message = ""+seed; System.out.println("send: "+seed); writer.write(message.getBytes()); writer.flush(); Thread.sleep(1000); } } catch (InterruptedException | IOException e) { //something }finally{ try { writer.close(); } catch (IOException e) { //something } } } }public static void main(String[] args) throws InterruptedException, IOException { PipedInputStream inputStream = new PipedInputStream(); PipedOutputStream outputStream = new PipedOutputStream(); //管道连接 inputStream.connect(outputStream); //或 outputStream.connect(inputStream); //创建读写线程 Thread reader = new Thread(new ReadClient(inputStream)); reader.start(); Thread.sleep(2000); Thread writer = new Thread(new WriteClient(outputStream)); writer.start(); }
结果:
send: 1 get: 1 send: 2 get: 2 send: 3 get: 3 在main方法中,读的线程先启动了,所以在read时会阻塞直到writer线程开始写数据。如果writer先启动,数据也不会丢失,会一直写入到管道中。直到reader线程去读取它。