JAVA中管道流(线程间通讯)例子
JAVA中管道流(线程间通讯)例子
JAVA中管道通讯(线程间通讯)例子
下面例子中使用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
运行后效果如下:
JAVA中管道流(线程间通讯)例子
https://www.dearcloud.cn/2012/09/17/20200310-cnblogs-old-posts/20120917-JAVA中管道流(线程间通讯)例子/