java中write方法报错_Java中管道报错:Write end dead
今天看了下關于管道的通信,Java中的管道只能在同一進程的不同線程間通信。今天測試兩個線程進行通信發現報錯。下面是我測試的代碼。
package com.wpl.testIO;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class IoOne {
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
final PipedOutputStream outputStream=new PipedOutputStream();
final PipedInputStream inputStream=new PipedInputStream(outputStream);
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
try {
outputStream.write("Hello world".getBytes());
//outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread t2=new Thread(new Runnable() {
@Override
public void run() {
try {
int count=inputStream.read();
while(count!=-1&&outputStream!=null)
{
System.out.print((char) count);
count=inputStream.read();
}
//inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}
報錯的圖片如下。
值能夠讀出來,但是最后還是會報錯,不知道為何,往上看了很多解決辦法,也沒有用,同時我的輸入和輸出并沒有顯示的關閉,而是使用jdk1.7中的try-resources代替顯示地調用close方法的方式。后來發現問題就出在這里將代碼簡單改寫下,就沒有報錯了。
package com.wpl.testIO;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class IoOne {
public static void main(String[] args) throws IOException {
final PipedOutputStream outputStream=new PipedOutputStream();
final PipedInputStream inputStream=new PipedInputStream(outputStream);
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
try {
outputStream.write("Hello world".getBytes());
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread t2=new Thread(new Runnable() {
@Override
public void run() {
try {
int count=inputStream.read();
while(count!=-1&&outputStream!=null)
{
System.out.print((char) count);
count=inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}
其實還是資源沒有關閉的問題,下次應該注意。
標簽:
總結
以上是生活随笔為你收集整理的java中write方法报错_Java中管道报错:Write end dead的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ES6-24 生成器与迭代器的应用
- 下一篇: Webpack基础