Skip to content

Commit 3c61df0

Browse files
committed
管道输入输出流的的使用-同一个JVM中,两个线程直接的字节流通信
1 parent a9a9dca commit 3c61df0

1 file changed

Lines changed: 66 additions & 0 deletions

File tree

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package org.javacore.io;
2+
3+
import java.io.IOException;
4+
import java.io.PipedInputStream;
5+
import java.io.PipedOutputStream;
6+
/*
7+
* Copyright [2015] [Jeff Lee]
8+
*
9+
* Licensed under the Apache License, Version 2.0 (the "License");
10+
* you may not use this file except in compliance with the License.
11+
* You may obtain a copy of the License at
12+
*
13+
* http://www.apache.org/licenses/LICENSE-2.0
14+
*
15+
* Unless required by applicable law or agreed to in writing, software
16+
* distributed under the License is distributed on an "AS IS" BASIS,
17+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18+
* See the License for the specific language governing permissions and
19+
* limitations under the License.
20+
*/
21+
22+
/**
23+
* @author Jeff Lee
24+
* @since 2015-7-30 21:58:18
25+
* 管道输入输出流的使用
26+
* 同一个JVM中,两个线程直接的字节流通信
27+
*/
28+
public class PipeStreamT {
29+
public static void main(String[] args) throws IOException {
30+
// 创建管道输出流
31+
final PipedOutputStream output = new PipedOutputStream();
32+
// 创建管道输入流,并连接到管道输出流
33+
@SuppressWarnings("resource")
34+
final PipedInputStream input = new PipedInputStream(output);
35+
//final PipedInputStream input = new PipedInputStream();
36+
//input.connect(output); // 等价于
37+
38+
Thread outputThread = new Thread(new Runnable() {
39+
@Override
40+
public void run() {
41+
try {
42+
// 将指定的字节数组写入管道输出流
43+
output.write("Hello,PipedStream!".getBytes());
44+
} catch (IOException e) {}
45+
}
46+
});
47+
48+
Thread inputThread = new Thread(new Runnable() {
49+
@Override
50+
public void run() {
51+
try {
52+
// 读取管道输入流中的下一个数据字节
53+
int data = input.read();
54+
while( data != -1) {
55+
System.out.print((char) data);
56+
// 再次读取下一个字节
57+
data = input.read();
58+
}
59+
} catch (IOException e){}
60+
}
61+
});
62+
63+
outputThread.start();
64+
inputThread.start();
65+
}
66+
}

0 commit comments

Comments
 (0)