生产者消费者模型 JAVA


生产者消费者问题(Producer-consumer problem),也称有限缓冲问题(Bounded-buffer problem),是一个多线程同步问题的经典案例。生产者生成一定量的数据放到缓冲区中,然后重复此过程;与此同时,消费者也在缓冲区消耗这些数据。生产者和消费者之间必须保持同步,要保证生产者不会在缓冲区满时放入数据,消费者也不会在缓冲区空时消耗数据。



实现该模型具有不止一种办法,本篇采用wait(),notifyAll()来实现,具体说明见代码注释。
生产者和消费者我设定了一定的sleep时间,以贴合实际并方便观察结果。

仓库


public class Storage {	
	//仓库类
	
	//仓库的最大容量
	private final int maxSize=10;
	
	//仓库当前货物数量
	private int currentSize=0;
	
	//生产方法
	public synchronized void  produce() {	//注意一定要使用while循环阻塞不满足条件的情况
		while(currentSize>=maxSize) {		//wait()之后再次被唤醒将从wait后继续执行 所以使用if不行
			System.out.println(Thread.currentThread().getName()+"仓库已满");
			try {
				wait();
			} catch (InterruptedException e) {
				
			}
		}
		currentSize++;
		System.out.println(Thread.currentThread().getName()+"生产了一个产品 现库存为"+currentSize);
		notifyAll();
	}
	
	//消费方法
	public synchronized void consume() {
		while(currentSize==0) {
			System.out.println(Thread.currentThread().getName()+"仓库已空");
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO: handle exception
			}
		}
		currentSize--;
		System.out.println(Thread.currentThread().getName()+"消费类一个产品 现库存为"+currentSize);
		notifyAll();
	}
}

生产者


public class Producer implements Runnable {
	
	private Storage s;
	
	public Producer(Storage s) {
		this.s = s;
	}

	@Override
	public void run() {
		while(true) {
			try {
				Thread.sleep(1000);
				s.produce();
			} catch (InterruptedException e) {
				// TODO: handle exception
			}
		}
	}

}

消费者


public class Consumer implements Runnable {
	
	private Storage s;
	
	public Consumer(Storage s) {
		this.s = s;
	}

	@Override
	public void run() {
		while(true) {
			try {
				Thread.sleep(3000);
				s.consume();
			} catch (InterruptedException e) {
				// TODO: handle exception
			}
		}
	}

}

测试


public class test {
	public static void main(String[] args) {
		Storage s=new Storage();
		new Thread(new Producer(s),"生产者1").start();
		new Thread(new Producer(s),"生产者2").start();
		new Thread(new Producer(s),"生产者3").start();
		
		new Thread(new Consumer(s),"消费者1").start();
		new Thread(new Consumer(s),"消费者2").start();
		new Thread(new Consumer(s),"消费者3").start();
	}
}

文章作者: Kong Aobo
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Kong Aobo !
  目录