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

版权声明:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41054313/article/details/89432686

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

线程流必须输入输出一起使用只使用一个会抛出 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:线程间通讯不仅仅只有这一种方式,而且实际开发中,很少会用到这种方式,仅作为一种了解方式

猜你喜欢

转载自blog.csdn.net/qq_41054313/article/details/89432686