java中write方法报错_Java中管道报错:Write end dead
发布日期:2021-08-13 07:44:20 浏览次数:12 分类:技术文章

本文共 2005 字,大约阅读时间需要 6 分钟。

今天看了下关于管道的通信,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();

}

}

报错的图片如下。

a98afa80bd4fbfdf3cd286109c6674fa

值能够读出来,但是最后还是会报错,不知道为何,往上看了很多解决办法,也没有用,同时我的输入和输出并没有显示的关闭,而是使用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();

}

}

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

标签:

转载地址:https://blog.csdn.net/weixin_30679649/article/details/114793445 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:java多属性的map_java - 具有多个参数的MapStruct QualifiedByName - 堆栈内存溢出
下一篇:java延迟覆盖_高效Java第九条覆盖equals时总要覆盖hashCode

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月24日 08时53分41秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章