0
請考慮以下測試代碼。使用帶管道流的普通流寫入器/閱讀器
我想知道是否可以使用管道流,如「正常」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();
}
}
}
}
注意註釋行: // message = reader.readLine(); 我一開始就試過這個,它一直在阻塞,所以爲什麼我現在加了那個電話。 – csvan