Java中管道报错:Write end dead

来源:互联网 发布:mac landesk 卸载 编辑:程序博客网 时间:2024/06/04 18:53

今天看了下关于管道的通信,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() {@Overridepublic void run() {try {outputStream.write("Hello world".getBytes());//outputStream.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});Thread t2=new Thread(new Runnable() {@Overridepublic 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() {@Overridepublic void run() {try {outputStream.write("Hello world".getBytes());outputStream.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});Thread t2=new Thread(new Runnable() {@Overridepublic 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();}}

其实还是资源没有关闭的问题,下次应该注意。

阅读全文
1 0