1、管道流的使用
1 package cn.kongxh.io6; 2 import java.io.* ; 3 class Send implements Runnable{ // 线程类 4 private PipedOutputStream pos = null ; // 管道输出流 5 public Send(){ 6 this.pos = new PipedOutputStream() ; // 实例化输出流 7 } 8 public void run(){ 9 String str = "Hello World!!!" ; // 要输出的内容 10 try{ 11 this.pos.write(str.getBytes()) ; 12 }catch(IOException e){ 13 e.printStackTrace() ; 14 } 15 try{ 16 this.pos.close() ; 17 }catch(IOException e){ 18 e.printStackTrace() ; 19 } 20 } 21 public PipedOutputStream getPos(){ // 得到此线程的管道输出流 22 return this.pos ; 23 } 24 }; 25 class Receive implements Runnable{ 26 private PipedInputStream pis = null ; // 管道输入流 27 public Receive(){ 28 this.pis = new PipedInputStream() ; // 实例化输入流 29 } 30 public void run(){ 31 byte b[] = new byte[1024] ; // 接收内容 32 int len = 0 ; 33 try{ 34 len = this.pis.read(b) ; // 读取内容 35 }catch(IOException e){ 36 e.printStackTrace() ; 37 } 38 try{ 39 this.pis.close() ; // 关闭 40 }catch(IOException e){ 41 e.printStackTrace() ; 42 } 43 System.out.println("接收的内容为:" + new String(b,0,len)) ; 44 } 45 public PipedInputStream getPis(){ 46 return this.pis ; 47 } 48 }; 49 public class PipedDemo{ 50 public static void main(String args[]){ 51 Send s = new Send() ; 52 Receive r = new Receive() ; 53 try{ 54 s.getPos().connect(r.getPis()) ; // 连接管道 55 }catch(IOException e){ 56 e.printStackTrace() ; 57 } 58 new Thread(s).start() ; // 启动线程 59 new Thread(r).start() ; // 启动线程 60 } 61 };