lay*_*ece 9 java multithreading ioexception
在以下情况下发生写入结束异常:两个线程:
A: PipedOutputStream put = new PipedOutputStream();
String msg = "MESSAGE";
output.wirte(msg.getBytes());
output.flush();
B: PipedInputStream get = new PipedOutputStream(A.put);
byte[] get_msg = new byte[1024];
get.read(get_msg);
Run Code Online (Sandbox Code Playgroud)
情况如下:A和B同时运行,A写入管道,B读取它.B只是从管道中读取并清除了该管道的缓冲区.然后A不会在未知的时间间隔内将msg写入管道.但是,在某一时刻,B再次读取管道并java.io.IOException: write end dead
发生,因为管道的缓冲区仍然是空的.而且我不想睡眠()线程B等待A写管道,这也是不稳定的.如何避免这个问题并解决它?谢谢
Pra*_*ore 17
如果您有以下情况,将会出现"写死亡"例外:
要解决此异常,只需在完成向管道流写入和读取字节后,在Thread的runnable中关闭管道流.
以下是一些示例代码:
final PipedOutputStream output = new PipedOutputStream();
final PipedInputStream input = new PipedInputStream(output);
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
output.write("Hello Piped Streams!! Used for Inter Thread Communication".getBytes());
output.close();
} catch(IOException io) {
io.printStackTrace();
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
int data;
while((data = input.read()) != -1) {
System.out.println(data + " ===> " + (char)data);
}
input.close();
} catch(IOException io) {
io.printStackTrace();
}
}
});
thread1.start();
thread2.start();
Run Code Online (Sandbox Code Playgroud)
完整的代码在这里:https://github.com/prabhash1785/Java/blob/master/JavaCodeSnippets/src/com/prabhash/java/io/PipedStreams.java
有关详细信息,请查看这个不错的博客:https://techtavern.wordpress.com/2008/07/16/whats-this-ioexception-write-end-dead/
小智 6
你需要关闭 PipedOutputStream,在写线程完成之前(当然在所有数据都写完之后)。当没有写入线程且写入器未正确关闭时,PipedInputStream 在 read() 上抛出此异常