java io 不同线程之间的通信

java IO 包中的管道 PipedInputStream,PipedOutStream 为运行在同一个JVM 下的两个线程之间通信提供通信能力,所以管道也可以作为数据源和目标媒介。

注意:java中的管道,不能在两个不同的JVM 之间的线程之间进行通信,概念上java中的管道 不同于Unix、Linux系统中的管道。在Unix,Linux 中运行在不同地址空间进程可以通过通道通信。在java中通信的双方应该是运行在同一个进程中的不同线程。

/**
	 * 学习 通道 pipe 在不同线程之间的通信
	 * @throws IOException
	 * @throws InterruptedException 
	 */
	public static void testPipeExample() throws IOException, InterruptedException{
		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 world pipe!".getBytes());
				} catch (IOException e) {
					e.printStackTrace();
				}finally{
					try {
						<span style="color:#ff0000;">output.close();</span>
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		});
		
		Thread thread2 = new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					int data = -1;
					while((data=input.read())!=-1){
						System.out.print((char)data);
					}
					
				} catch (IOException e) {
					e.printStackTrace();
				}finally{
					try {
						input.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					
				}
			}
		});
		
		thread1.start();
		thread2.start();
		
		
	}


如果将output.close 与input.close 放在一起,就不抛出异常:  Write end dead 

原因是:在input.read之前,需要确保output管道是关闭的,也就是说,通道的内容是已经确定下来的,不可能再有write新内容了.(个人理解)

原文地址:点击打开链接


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值