16.5管道流

管道流的主要作用是可以进行两个线程间的通讯,分为管道输出流(PipedOutputStream、PipedWriter)、管道输入流(PipedInputStream、PipedReader)

  • 【PipedOutputStream】管道连接:public void connect(PipedInputStream snk) throws IOException
  • 【PipedWriter】管道连接:public void connect​(PipedReader snk) throws IOException
    管道流(字节流)
    在这里插入图片描述
    管道流(字符流)
    在这里插入图片描述
    范例:使用字节管道流实现线程通信
package com.lxh.sixteenchapter;

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

public class JavaIODemo420 {
       public static void main(String[] args) throws IOException {
    	   SendThread  send=new SendThread();
    	   ReceiveThread receive=new ReceiveThread();
    	   send.getOutput().connect(receive.getInput());//管道连接
    	   new Thread(send,"消息发送线程").start();
    	   new Thread(receive,"消息接收线程").start();
	}
}

class SendThread implements Runnable{     //发送消息线程
   private PipedOutputStream output;
   
	public PipedOutputStream getOutput() {
	return output;
}

public void setOutput(PipedOutputStream output) {
	this.output = output;
}
	public SendThread() {
	this.output = new  PipedOutputStream();
}
	@Override
	public void run() {
		try {
			this.output.write("您好?请问需要帮助吗?".getBytes());
		} catch (IOException e) {
			
			e.printStackTrace();
		}finally {
			if(output!=null) {
				try {
					output.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
}

class ReceiveThread implements Runnable{   //接收信息线程数据

	private PipedInputStream input;
	
	public ReceiveThread() {
	
	this.input =new PipedInputStream();
}

	public PipedInputStream getInput() {
		return input;
	}

	public void setInput(PipedInputStream input) {
		this.input = input;
	}

	@Override
	public void run() {
		byte[] data=new byte[1024];
		int len=0;
		ByteArrayOutputStream bos=new ByteArrayOutputStream();
		try {
			while((len=input.read(data))!=-1) {
				bos.write(data,0,len);
			}
			System.out.println(new String(bos.toByteArray()));
		} catch (IOException e) {
		
			e.printStackTrace();
		}finally {
			if(input!=null) {
				try {
					input.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}
	
}

执行结果

您好?请问需要帮助吗?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章