首页 > 编程语言 > 详细

Java 生产者消费者模型

时间:2021-05-29 13:17:26      阅读:17      评论:0      收藏:0      [点我收藏+]

生产者消费者模型(多线程) 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();
	}
}

Java 生产者消费者模型

原文:https://www.cnblogs.com/kongaobo/p/14824844.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!