管道通讯,使用管道通讯进行数据交流(PipeInputStream)

想了解一下,管道之间是怎样进行通讯的,于是看到网上的做的一个Demo,于是记录下来,方便学习

写一个消息生产者


/**
 * @author chenxihua
 * @Date 2018年9月17日
 * 
 * 我们以数字替代产品 生产者每5秒提供5个产品,放入管道
 */
public class MyProducer extends Thread {
	
	private PipedOutputStream outputStream;
	 
	public MyProducer(PipedOutputStream outputStream) {
		this.outputStream = outputStream;
	}
 
	@Override
	public void run() {
		while (true) {
			try {
				for (int i = 0; i < 5; i++) {
					outputStream.write(i);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}

写一个消息消费者

/**
 * @author chenxihua
 * @Date 2018年9月17日
 * 
 * 消费者每0.5秒从管道中取1件产品,并打印剩余产品数量,并打印产品信息(以数字替代)
 */
public class MyConsumer extends Thread {
	
	private PipedInputStream inputStream;
	 
	public MyConsumer(PipedInputStream inputStream) {
		this.inputStream = inputStream;
	}
 
	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			try {
				int count = inputStream.available();
				if (count > 0) {
					System.out.println("rest product count: " + count);
					System.out.println("get product: " + inputStream.read());
				}
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
}

然后写一个测试实例:

/**
 * @author chenxihua
 * @Date 2018年9月17日
 */
public class PipeTest {
	
	public static void main(String[] args) {
		 
		PipedOutputStream pos = new PipedOutputStream();
		PipedInputStream pis = new PipedInputStream();
		try {
			pis.connect(pos);
		} catch (IOException e) {
			e.printStackTrace();
		}
		new MyProducer(pos).start();
		new MyConsumer(pis).start();
	}
}

嗯,到这里应该没问题了,管道之间的通讯,最主要的还是connect()方法,它是链接数据输入与数据输出的方法。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值