Java 实现生产者与消费者(二)

本文介绍了一种在实际开发中实现生产者与消费者模式的方法。通过将生产与消费环节封装为同步函数并放入Resource类中,提高了代码的复用性和易用性。示例代码展示了如何使用线程进行生产与消费操作。

       在上篇博客中简单实现了生产者与消费者之间的通信,本片博客讲的是在实际开发当中是怎样实现二者之间的通信的。实际开发中将生产与消费的环节封装成函数放在了resource里面,这样在生产与消费的时候就更加的便捷,提高了代码的复用性。代码如下:

package threadCommunication;

//生产者和消费者共享的资源
class Resource{
	String name;
	String sex;
	boolean flag=false;
	
	//将生产的环节封装成resource里面,并且封装成同步函数
	public synchronized void produce(String name,String sex){
		if(flag){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		this.name=name;
		this.sex=sex;
		System.out.println("输入:"+name+"性别:"+sex);
		this.flag=true;
		this.notify();
	}
	
	//同理将消费者封装到resource里面,封装成同步函数
	public synchronized void consume(){
		if(!flag){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		System.out.println("输出:"+this.name+"性别:"+this.sex);
		this.flag=false;
		this.notify();
	}
}

//输入,代表的是生产者
class Input implements Runnable{
	Resource r;
	Input(Resource r){
		this.r=r;
	}
	public void run() {
		int x=1;
		while(true){
			r.produce("小光"+x, "男");
			x++;
			if(x>10)
				x=1;
		}
		
	}
}

//输出,代表的是消费者
 class Output implements Runnable{
	Resource r;
	Output(Resource r){
		this.r=r;
	}
	public void run() {
		while(true){
			r.consume();
		}
		
	}
}
public class InputOutput2 {

	/**
	 * @param args
	 * 
	 */
	
	public static void main(String[] args) {
		Resource r=new Resource();
		Input in=new Input(r);
		Output out=new Output(r);
		new Thread(in).start();
		new Thread(out).start();

	}

}
运行结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值