Java IO流之管道流

版权声明:LemonSnm https://blog.csdn.net/LemonSnm/article/details/89886932

管道流:

管道输入流应该连接到管道输出流;管道输入流提供要写入管道输出流的所有字节数据。通常,数据由某个线程从PipedInputStream对象读取,并由其他线程将其写入到相应的PipedOutputStream。

不建议对这两个对象尝试使用单个线程,因为这样可能死锁线程。管道输入流包含一个缓冲区,可在缓冲区限定的范围内将读操作和写操作分离开。如果向连接管道输出流提供数据字节的线程不再存在,则认为该管道已损坏。

应用: 

用于线程之间的数据通讯 

 代码示例:

package com.lemon;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/**
 * 管道流测试: 一个线程写入,一个线程读取
 * 作用:用于线程之间的数据通讯
 * @author lemonSun
 *
 * 2019年5月6日下午5:49:06
 */
public class PipedStreamDemo {

	public static void main(String[] args) {
		
		PipedInputStream pis = new PipedInputStream();
		PipedOutputStream pos = new PipedOutputStream();
		
		try {
			pis.connect(pos); //两个管道链接
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		ReadThread readThread = new ReadThread(pis);
		WriteThread writeThread = new WriteThread(pos);
		
		//先启动读,阻塞,等待写的线程启动
		new Thread(readThread).start();
		new Thread(writeThread).start();
	}
	
}

	//读取数据的线程
	class ReadThread implements Runnable{
		//输入管道流
		PipedInputStream pis;

		public ReadThread(PipedInputStream pis) {
			this.pis = pis;
		}
		
		public void run() {
			
			//管道输入流
			try {
				byte[] bytes = new byte[1024];
				int len = pis.read(bytes); //read阻塞
				String s = new String(bytes,0,len);
				System.out.println("读到:" + s);
				pis.close();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	//写入数据的线程
	class WriteThread implements Runnable{
		
		//输出管道流
		private PipedOutputStream pos; 

		public WriteThread(PipedOutputStream pos) {
			this.pos = pos;
		}
		
		public void run() {
			try {
				//管道输出流
				pos.write("这里是输出管道流".getBytes());
				pos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


猜你喜欢

转载自blog.csdn.net/LemonSnm/article/details/89886932