Java消费者生产者问题

本文介绍了一个典型的生产者消费者模式实现案例,通过两个生产者线程和两个消费者线程的交互,确保了生产与消费的平衡。生产和消费的数量由随机数决定,并且生产者和消费者的活动受到同步控制,以避免缓冲池中的资源超过1000。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 一个线程作为生产者,一个线程作为消费者。生产者和消费者在同时执行。
 *  生产者每生产一次消费者就消费一次。生产和消费的数量用随机数来表示。
 * 要求:生产者的数量和上次消费后的剩余数量和不大于1000.
 * sleep:可以指定休眠的时间,如果没有其他操作,那么到点自然醒。
 * 如果sleep有锁资源,那么不释放代码执行权,sleep是Thread的类方法
 * wait:可以指定也可以不指定休眠时间。
 * 如果有所资源,那么释放锁,也释放执行权。
 * 是属于Object的方法。使用等待唤醒机制是,和notify方法配合使用
 * 调用等待唤醒内容锁资源必须一致
 */
public class Demo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Product p=new Product();
		new Thread(new Producer(p),"生产者").start();
		new Thread(new Producer(p),"生产者").start();
		new Thread(new Consumer(p),"消费者").start();
		new Thread(new Consumer(p),"消费者").start();
	}

}
class Product{
	private int count=0;
	private boolean flag=true;
	
	public synchronized void add(){
		while(flag==false){
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		int max=1000-count;
		int num=(int)(Math.random()*(max+1));
		count+=num;
		System.out.println(Thread.currentThread().getName()+":"+num+"缓冲池中剩余资源:"+count);
		flag=false;
		notifyAll();
	}
	public synchronized void remove(){
		while(flag==true){
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		int num=(int)(Math.random()*(count+1));
		count-=num;
		System.out.println(Thread.currentThread().getName()+":"+num+"缓冲池中剩余资源:"+count);
		flag=true;
		notifyAll();
	}
}
class Consumer implements Runnable{
	private Product p;
	public Consumer(Product p) {
		super();
		this.p = p;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true){
			p.remove();
		}
	}
	
}
class Producer implements Runnable{
	private Product p;
	public Producer(Product p) {
		super();
		this.p = p;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true){
			p.add();
		}
	}
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值