JAVA中管道通讯(线程间通讯)例子

来源:互联网 发布:天猫双十一直播数据 编辑:程序博客网 时间:2024/05/16 11:32

下面例子中使用Java中的PipedInputStream类和PipedOutputStream类,给大家演示如何在Java中实现线程间的数据传送。

 

  

复制代码
 1 package lesson.io.test; 2   3  import java.io.*; 4   5  public class TestPiped 6  { 7   8      public static void main(String[] args) 9      {10          11          Sender sender = new Sender();12          Recive recive = new Recive();13          PipedInputStream pi=recive.getPipedInputputStream();14          PipedOutputStream po=sender.getPipedOutputStream();15          try16          {17              pi.connect(po);18          } catch (IOException e)19          {20              System.out.println(e.getMessage());21          }22          sender.start();23          recive.start();24          25      26      }27  28  }29  30  class Sender extends Thread31  {32       PipedOutputStream out = null;33  34      public PipedOutputStream getPipedOutputStream()35      {36          out = new PipedOutputStream();37          return out;38      }39  40      @Override41      public void run()42      {43          44          try45          {46              out.write("Hello , Reciver!".getBytes());47          } catch (IOException e)48          {49              System.out.println(e.getMessage());50          }51          try52          {53              out.close();54          } catch (IOException e)55          {56              System.out.println(e.getMessage());57          }58  59      }60  61  }62  63  64  class Recive extends Thread65  {66      PipedInputStream in = null;67  68      public PipedInputStream getPipedInputputStream()69      {70          in = new PipedInputStream();71          return in;72      }73  74      @Override75      public void run()76      {77      78          byte[] bys = new byte[1024];79          try80          {81              in.read(bys);82              System.out.println("读取到的信息:" + new String(bys).trim());83              in.close();84          } catch (IOException e)85          {86              System.out.println(e.getMessage());87          }88  89      }90  }91  
0 0
原创粉丝点击