JavaSE基础使用管道流实现生产消费者模式

使用管道流实现生产消费者模式

package com.thread.cooperation;

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

/** 
 * @ClassName: 
 * @author: YDJ
 * @Date: 2019年11月3日 下午10:59:13
 * @description: 使用管道流实现生产消费者模式
 */

public class Demo04 {
	public static void main(String[] args) {
		/**
		 * 创建管道输出流
		 */
		PipedOutputStream pos = new PipedOutputStream();
		/**
		 * 创建管道输入流
		 */
		PipedInputStream pis = new PipedInputStream();
		
		try {
			//将管道输入流与输出流连接, 这个过程也可以通过重载的构造函数来实现
			pos.connect(pis);
		} catch (IOException e) {
			e.printStackTrace();
		}
		//创建生产者线程
		PipeProducer p = new PipeProducer(pos,"xixi");
		//创建消费者线程
		pipeConsumer c1 = new pipeConsumer(pis, "lili");
		pipeConsumer c2 = new pipeConsumer(pis, "gaogao");
		
		//启动线程
		p.start();
		c1.start();
		c2.start();
		
	}
}

/**
 * 生产者线程(与一个管道输入流相关)
 * @author YDJ
 *
 */
class PipeProducer extends Thread{
	private PipedOutputStream pos;

	public PipeProducer(PipedOutputStream pos,String name) {
		super(name);
		this.pos = pos;
	}
	
	@Override
	public void run() {
		int i = 0;
		try {
			while (true) {
			Thread.sleep(2000);
			System.out.println(Thread.currentThread().getName()+"product:"+i);
			pos.write(i);
			i++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	
}

/**
 * 消费者线程(与一个管道输入流相关)
 * @author YDJ
 *
 */
class pipeConsumer extends Thread{
	private PipedInputStream pis;

	public pipeConsumer(PipedInputStream pis,String name) {
		super(name);
		this.pis = pis;
	}
	@Override
	public void run() {
		
		try {
			while (true) {
				System.out.println(Thread.currentThread().getName()+"consumer:"+pis.read());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值