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

本文通过Java中的PipedInputStream和PipedOutputStream类,展示了如何在不同线程之间进行数据传递。主要包括发送者和接收者两个线程实例,其中发送者线程将消息发送至接收者线程,接收者线程负责接收并打印接收到的消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面例子中使用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          try
16          {
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 Thread
31  {
32       PipedOutputStream out = null;
33  
34      public PipedOutputStream getPipedOutputStream()
35      {
36          out = new PipedOutputStream();
37          return out;
38      }
39  
40      @Override
41      public void run()
42      {
43          
44          try
45          {
46              out.write("Hello , Reciver!".getBytes());
47          } catch (IOException e)
48          {
49              System.out.println(e.getMessage());
50          }
51          try
52          {
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 Thread
65  {
66      PipedInputStream in = null;
67  
68      public PipedInputStream getPipedInputputStream()
69      {
70          in = new PipedInputStream();
71          return in;
72      }
73  
74      @Override
75      public void run()
76      {
77      
78          byte[] bys = new byte[1024];
79          try
80          {
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  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值