考虑以下测试代码。
我试图找出我是否可以使用像“普通” I/O 流这样的管道流,以及常用的 Reader 和 Writer 实现(具体来说,我正在处理的代码库的另一部分要求我使用 OutputStreamWriter)。
这里的问题是读取端似乎没有显示任何内容。该程序至少似乎正确地将消息写入管道的写入端,但是当尝试从另一端读取时,我会无限期地阻塞,或者如果我(在这种情况下)检查可用字节,则调用返回 0 .
我究竟做错了什么?
public class PipeTest {
private InputStream input;
private OutputStream output;
public PipeTest() throws IOException {
input = new PipedInputStream();
output = new PipedOutputStream((PipedInputStream)input);
}
public void start() {
Stuff1 stuff1 = new Stuff1(input);
Stuff2 stuff2 = new Stuff2(output);
Thread thread = new Thread(stuff1);
thread.start();
Thread thread2 = new Thread(stuff2);
thread2.start();
}
public static void main(String[] args) throws IOException {
new PipeTest().start();
}
private static class Stuff1 implements Runnable {
InputStream inputStream;
public Stuff1(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public void run() {
String message;
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
//message = reader.readLine();
System.out.println("Got message!");
System.out.println(inputStream.available());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static class Stuff2 implements Runnable {
OutputStream outputStream;
public Stuff2(OutputStream outputStream) {
this.outputStream = outputStream;
}
@Override
public void run() {
String message = "Hej!!\n";
OutputStreamWriter writer = new OutputStreamWriter(outputStream);
try {
writer.write(message);
System.out.println("Wrote message!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}