Java I/O系统是建立在数据流概念之上的,而在UNIX/Linux中有一个类似的概念,就是管道,它具有将一个程序的输出当作另一个程序的输入的能力。在Java中,可以使用管道流进行线程之间的通信,输入流和输出流必须相连接,这样的通信有别于一般的Shared Data通信,其不需要一个共享的数据空间。

 

package lesson.io.test;
 
 import java.io.*;
 
 public class TestPiped
 {
 
     public static void main(String[] args)
     {
         
         Sender sender = new Sender();
         Recive recive = new Recive();
         PipedInputStream pi=recive.getPipedInputputStream();
         PipedOutputStream po=sender.getPipedOutputStream();
         try
         {
             pi.connect(po);
         } catch (IOException e)
         {
             System.out.println(e.getMessage());
         }
         sender.start();
         recive.start();
         
     
     }
 
 }
 
 class Sender extends Thread
 {
      PipedOutputStream out = null;
 
     public PipedOutputStream getPipedOutputStream()
     {
         out = new PipedOutputStream();
         return out;
     }
 
     @Override
     public void run()
     {
         
         try
         {
             out.write("Hello , Reciver!".getBytes());
         } catch (IOException e)
         {
             System.out.println(e.getMessage());
         }
         try
         {
             out.close();
         } catch (IOException e)
         {
             System.out.println(e.getMessage());
         }
 
     }
 
 }
 
 
 class Recive extends Thread
 {
     PipedInputStream in = null;
 
     public PipedInputStream getPipedInputputStream()
     {
         in = new PipedInputStream();
         return in;
     }
 
     @Override
     public void run()
     {
     
         byte[] bys = new byte[1024];
         try
         {
             in.read(bys);
             System.out.println("读取到的信息:" + new String(bys).trim());
             in.close();
         } catch (IOException e)
         {
             System.out.println(e.getMessage());
         }
 
     }
 }