生产者-仓库-消费者

生产者-仓库-消费者

发现一个单词 Z-turn  据说是“折腾”这个词的英译,好传神的说。

生产者-仓库-消费者,任何语言里都会有的东西,如同Hello!,更应该说是计算机基础里的东西,还依稀记得曾经的一课本上看到过它。

生产者Producer.java:

 /**
 *
 */
package cn.hidehai.thread;

/**
 * @author nsir
 * 生产者模型
 */
public class Producer extends Thread {
	private int number;
	private Storehouse shouse; //仓库

	public Producer(int number,Storehouse shouse) {
		this.number = number;
		this.shouse = shouse;
	}

	public void run(){
		//生产指定数量的产品
		  shouse.produce(number);
	}

}

消费者Consumer.java:

 /**
 * 
 */
package cn.hidehai.thread;

/**
 * @author nsir
 *消费者模型
 */
public class Consumer extends Thread {
	
	private int number;
	private Storehouse shouse;
	
	public Consumer(int number,Storehouse shouse) {
		this.number = number;
		this.shouse = shouse;
	}

	public void run() {
		//消费指定数量的产品
		shouse.cost(number);
	}

}

仓库Storehouse.java

 /**
 * 
 */
package cn.hidehai.thread;

import static cn.hidehai.thread.Print.*;
/**
 * @author nsir
 * 仓库模型
 */
public class Storehouse {
	
	public static final int max_number = 1000; // 仓库存储数量
	public int currentNumber; 		//仓库当前数量
	
	public Storehouse(int currentNumber) {
		this.currentNumber = currentNumber;
	}
	
	public synchronized void produce(int number){//生产
		while(currentNumber+number > max_number){
			print("超过仓库容量数,暂停生产!\n计划生产:"+number+"仓库剩余:"+currentNumber);
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		currentNumber += number; //进行生产
		print("生产数:"+number+" 仓库剩余:"+currentNumber);
		
		
		notifyAll();  //唤醒等待的线程
	}
	
	public synchronized void cost(int number){//消费
		while(currentNumber < number){
			print("仓库剩余数量不足,不能消费!\n计划消费:"+number+"仓库剩余:"+currentNumber);
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		currentNumber -= number;
		print("消费数:"+number+" 仓库剩余:"+currentNumber);
		notifyAll();
	}

}

测试类Market.java

 /**
 * 
 */
package cn.hidehai.thread;

import java.util.Random;

/**
 * @author nsir
 * 市场^^
 */
public class Market {
	
	public static int getRandNum(){
		return new Random().nextInt(10);
	}
	
	public static void main(String[] args){
		int i = 100;
		Storehouse sHoust = new Storehouse(15); // 初始化仓库
		Producer p1 = new Producer(getRandNum(),sHoust);  //生产消息
		Consumer c1 = new Consumer(getRandNum(),sHoust);  //消费消息
		Producer p2 = new Producer(getRandNum(),sHoust);  
		Consumer c2 = new Consumer(getRandNum(),sHoust); 
		Producer p3 = new Producer(getRandNum(),sHoust);  
		Consumer c3 = new Consumer(getRandNum(),sHoust);  
		p1.start();
		c1.start();
		p2.start();
		c2.start();
		p3.start();
		c3.start();	
	}
}

留下回复