Java多线程——生产者消费者模式

生产消费者模式,实现功能:1.生产者和消费者同时运行(多线程)。2.实现生产完一个对象后然后消费者消费,而不是生产者生产到一半时被消费者消费(同步锁synchronized)。3.实现生产者生产一个消费者消费一个,而不是消费者消费同一个产品(Object类的wait方法和notify方法)。

public class Share {//共享数据对象
	private String name;
	private String gender;
	private boolean isEmpty = true;
	
	synchronized public void push(String name, String gender){
		try {
			if(!isEmpty){
					this.wait();
			}
		this.name = name;
		Thread.sleep(10);
		this.gender = gender;
		isEmpty = false;
		this.notify();
		} catch (InterruptedException e) {
		// TODO 自动生成的 catch 块
		e.printStackTrace();
		}
	}
	
	synchronized public void pick(){
		try {
			if(isEmpty){
				this.wait();
			}
			Thread.sleep(10);
			System.out.println(this.name+"------"+this.gender);
			this.isEmpty = true;
			this.notify();
		} catch (InterruptedException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
}

public class Producer implements Runnable{

	private Share share;
	
	public Producer(Share share){
		this.share = share;
	}

	@Override
	public void run() {
		for(int i = 0;i<50;i++){
			if(i%2==0){
				share.push("a", "男");
			}else{
				share.push("b", "女");
			}
//			try {
//				Thread.sleep(200);
//			} catch (InterruptedException e) {
//				// TODO 自动生成的 catch 块
//				e.printStackTrace();
//			}
		}
		
	}
	
}

public class Consumer implements Runnable {

	private Share share;
	
	public Consumer(Share share) {
		super();
		this.share = share;
	}


	@Override
	public void run() {
		for(int i = 0;i<50;i++){
//			try {
//				Thread.sleep(100);
//			} catch (InterruptedException e) {
//				// TODO 自动生成的 catch 块
//				e.printStackTrace();
//			}
			share.pick();
//			try {
//				Thread.sleep(100);
//			} catch (InterruptedException e) {
//				// TODO 自动生成的 catch 块
//				e.printStackTrace();
//			}
		}
	}

}

public class Test1 {

	public static void main(String[] args) {
		Share sh = new Share();
		new Thread(new Producer(sh)).start();
		new Thread(new Consumer(sh)).start();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值