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();
		
	}
	
}

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

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值