管道流用于线程之间的通信。
PipedInputStream类与PipedOutputStream类用于在应用程序中创建管道通信.一个PipedInputStream实例对象必须和一个PipedOutputStream实例对象进行连接而产生一个通信管道.PipedOutputStream可以向管道中写入数据,PipedIntputStream可以读取PipedOutputStream向管道中写入的数据.这两个类主要用来完成线程之间的通信.一个线程的PipedInputStream对象能够从另外一个线程的PipedOutputStream对象中读取数据.
一个线程的PipedInputStream对象从另外一个线程的PipedOutputStream对象读取输入。要使管道流有用,必须同时构造管道输入流和管道输出流。
一共有两种方式实现管道流:
方法1 : 使用Connect进行连接
写入管道:
代码 import java.io.IOException; import java.io.PipedOutputStream; public class Producer extends Thread { private PipedOutputStream pos; public Producer(PipedOutputStream pos) { this.pos = pos; } @Override public void run() { super.run(); try { pos.write("Hello".getBytes()); } catch (IOException e) { e.printStackTrace(); } } }
代码 import java.io.IOException; import java.io.PipedInputStream; public class Consumer extends Thread { private PipedInputStream pis; public Consumer(PipedInputStream pis) { this.pis = pis; } @Override public void run() { super.run(); byte[] b = new byte[100]; // 将数据保存在byte数组中 try { int len = pis.read(b); // 从数组中得到实际大小。 System.out.println(new String(b, 0, len)); pis.close(); } catch (IOException e) { e.printStackTrace(); } } }
PipedStreamTest import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; public class PipedStreamTest { public static void main(String[] args) { PipedOutputStream pos = new PipedOutputStream(); PipedInputStream pis = new PipedInputStream(); try { pos.connect(pis);// 连接管道 new Producer(pos).start();// 启动线程 new Consumer(pis).start();// 启动线程 } catch (IOException e) { e.printStackTrace(); } } }
方法2 : 是通过构造函数直接将某一个程序的输出作为另一个程序的输入,在定义对象时指明目标管道对象
Sender:
package Com.example.Pipe; import java.io.IOException; import java.io.PipedWriter; public class Sender extends Thread { private PipedWriter out =new PipedWriter(); public PipedWriter getPipedWriter() { return out; } public void run() { while(true) { for(char c='a';c<'z';c++){ try { out.write(c); sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
package Com.example.Pipe; import java.io.IOException; import java.io.PipedReader; public class Receiver extends Thread { private PipedReader in; public Receiver(Sender sender) throws IOException { in = new PipedReader(sender.getPipedWriter()); } public void run(){ try { while(true) { System.out.println("read"+(char)in.read()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package Com.example.Pipe; import java.io.IOException; import java.io.PipedWriter; import java.util.Random; public class Main { public static void main(String[] args) throws IOException { Sender sender = new Sender(); Receiver receiver = new Receiver(sender); sender.start(); receiver.start(); } }