二十一、使用Condition重写waitnotify生产者消费者模型案例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29479041/article/details/85092998
//生产者
public class PushTarget implements Runnable{
	private Tmail tmail;//销售平台
	public PushTarget(Tmail tmail) {
		this.tmail = tmail;
	}
	@Override
	public void run() {
		while(true) {//无限循环
			tmail.push();//生产
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
//消费者
public class TakeTarget implements Runnable{
	private Tmail tmail;//销售平台
	public TakeTarget(Tmail tmail) {
		this.tmail = tmail;
	}
	@Override
	public void run() {
		while(true) {//无限循环
			tmail.take();//消费
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
public class Tmail {
	private int count;//产品数量
	Lock lock = new ReentrantLock();
	Condition p = lock.newCondition();
	Condition t = lock.newCondition();
	public final int MAX_COUNT=10;//产品最大数量
	//生产
	public void push() {
		lock.lock();//加锁
		while(count>=MAX_COUNT) {//产品数量大于等于最大数量,生产者等待
			try {
				System.out.println(Thread.currentThread().getName()+"库存达到上线,生产者停止生产。。。。。");
				p.await();//生产者等待
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		count++;
		System.out.println(Thread.currentThread().getName()+"生产者生产,当前库存为:"+count);
		t.signal();//唤醒消费者
		lock.unlock();// 释放锁
	}
	//消费
	public void take() {
		lock.lock();//加锁
		while(count<=0) {// 产品数量为0,消费者等待
			try {
				System.out.println(Thread.currentThread().getName()+"当前库存为:"+count+",消费者等待。");
				t.await();//等待
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		count--;
		System.out.println(Thread.currentThread().getName()+"消费者消费。");
		p.signal();//唤醒生产者
		lock.unlock();// 释放锁
	}
	
	public static void main(String[] args) {
		Tmail tmail = new Tmail();
		PushTarget t = new PushTarget(tmail);
		TakeTarget t2 = new TakeTarget(tmail);
		new Thread(t).start();
		new Thread(t).start();
		new Thread(t).start();
		new Thread(t).start();
		new Thread(t).start();
		new Thread(t).start();
		new Thread(t2).start();
		new Thread(t2).start();
		new Thread(t2).start();
		new Thread(t2).start();
		new Thread(t2).start();
		new Thread(t2).start();
		new Thread(t2).start();
	}
}

猜你喜欢

转载自blog.csdn.net/qq_29479041/article/details/85092998