管道流

管道流的主要作用是可以进行两个线程间的通信

分为管道输出流(PipedOutputStream)管道输入流(PipedInputStream)

 

定义两个线程对象,在发送的线程类中定义了管道输出类,在接收的线程类中定义了管道的输入类,在操作时只需要使用PipedOutputStream类中提供的connection()方法就可以将两个线程冠带连接在一起,线程启动后会自动进行管道的输入和输出操作

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

//=================================================
// File Name       :	Pipe_demo
//------------------------------------------------------------------------------
// Author          :	Common




// 类名:Send
// 属性:
// 方法:
class Send implements Runnable{		//实现Runnable接口
	
	private PipedOutputStream pos = null;	//管道输出流
	
	public Send() {	//实例化输出流
		super();
		this.pos = new PipedOutputStream();
	}
	
	public PipedOutputStream getPos() {		//通过线程类得到输出流
		return pos;
	}

	@Override
	public void run() {
		// TODO 自动生成的方法存根
		String str = "HelloWord!!";
		try{
			this.pos.write(str.getBytes());		//输出信息
		}catch(IOException e){
			e.printStackTrace();
		}
		try{
			this.pos.close(); 							//关闭输出流
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
}

//类名:Receive
//属性:
//方法:
class Receive implements Runnable{		//实现Runnable接口
	
	private PipedInputStream pis = null;	//管道输入流
	
	public Receive() {	//实例化输出流
		super();
		this.pis = new PipedInputStream();
	}
	
	public PipedInputStream getPis() {		//通过线程类得到输入流
		return pis;
	}

	@Override
	public void run() {
		// TODO 自动生成的方法存根
		byte b[] = new byte[1024];	//实例化输入流
		int len = 0;
		try{
			len = this.pis.read(b);			//接收数据
		}catch(IOException e){
			e.printStackTrace();
		}
		try{
			this.pis.close(); 							//关闭输入流
		}catch(IOException e){
			e.printStackTrace();
		}
		System.out.println("接收的内容为"+new String(b,0,len));
	}
	
}

//主类
//Function        : 	Pipe_demo
public class Pipe_demo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Send s = new Send();
		Receive r = new Receive();
		try{
			s.getPos().connect(r.getPis());  	//连接管道
		}catch(IOException e){
			e.printStackTrace();
		}
		new Thread(s).start();
		new Thread(r).start();
	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值