管道流(线程流)——PipedInputStream、PipedOutputStream

线程流,顾名思义就是在线程之间传输数据的流。主要用途自然就是用于线程之间通讯。

线程流必须输入输出一起使用只使用一个会抛出 java.io.IOException: Pipe not connected 而且也不能一个对应多个 只能一对一,一对多会抛出 java.io.IOException: Already connected 

例:

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class Tests {
	/**
	 * 
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		PipedOutputStream os = new PipedOutputStream();
//		os.write("".getBytes());//解除注释,会抛出 java.io.IOException: Pipe not connected 
		PipedInputStream in = new PipedInputStream(os);

		//解除下面两行注释会抛出 java.io.IOException: Already connected
//		PipedInputStream in1 = new PipedInputStream(os);
//		new Tests().new B(in1).start();
		
		new Tests().new A(os).start();
		new Tests().new B(in).start();
		/**
		 * 除了可以在实例化这两个对象时将两个流对象绑定 ,
		 * 还可以通过调用 in.connect(PipedOutputStream src);方法来连接两个流
		 * 两个流只需要连接一次,不限制顺序,可以in.connect(os),也可以相反
		 */
	}
	class A extends Thread{
		PipedOutputStream os= null;
		public A(PipedOutputStream os) {
			super("A");
			this.os = os;
		}
		
		public void run() {
			while(true) {
				try {
					os.write("0123456789".getBytes());
					os.flush();
					System.err.println(this.getName()+" : "+"0123456789");
					Thread.sleep(1000);
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	class B extends Thread{
		PipedInputStream in = null;
		
		public B(PipedInputStream in) {
			super("B");
			this.in = in;
		}
		
		public void run() {
			byte[] b = new byte[10];
			int len = 0;
			try {
				while((len=in.read(b))>0) {
					System.out.println(this.getName()+" : "+new String(b,0,len));
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

ps:线程间通讯不仅仅只有这一种方式,而且实际开发中,很少会用到这种方式,仅作为一种了解方式

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dan淡淡的心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值