例子用java多线程模拟生产者消费者的例子,上代码,代码有注释说的清楚:
仓库
package day5;
/**
* <p>Title: Warehouse.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2014</p>
* @author 雪含心
* @date 2014年2月7日
*/
public class Warehouse {
private int MAXNUM = 100;
private int currentCount;
public Warehouse(int i) {
this.currentCount = i;
}
/**
* 生产者
* @param neednum
*/
public synchronized void produce(int neednum){
// 当当前的数量和生产的数量大于仓库容量时等待消费
while (currentCount + neednum > MAXNUM) {
try {
System.out.println("要生产的产品" + neednum + "个产品,超过仓库最大值" + MAXNUM);
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
currentCount += neednum;
System.out.println("已经生产了" + neednum + "个产品,现仓储量为" + currentCount);
notifyAll();
}
/**
* 消费者方法
* @param neednum
*/
public synchronized void consume(int neednum){
// 当当前的消费的数量大于库存时等待生产
while (currentCount < neednum) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
currentCount -= neednum;
System.out.println("已经消费了" + neednum + "个产品,现仓储量为" + currentCount);
notifyAll();
}
}
生产者
package day5;
/**
* <p>Title: Productor.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2014</p>
* @author 雪含心
* @date 2014年2月7日
*/
public class Producer extends Thread {
private Warehouse house;
private int neednum;
public Producer(Warehouse house, int neednum){
this.neednum = neednum;
this.house = house;
}
@Override
public void run() {
house.produce(neednum);
}
}
消费者
package day5;
/**
* <p>Title: Consumer.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2014</p>
* @author 雪含心
* @date 2014年2月7日
*/
public class Consumer extends Thread {
private Warehouse house;
private int neednum;
public Consumer(Warehouse house, int neednum){
this.neednum = neednum;
this.house = house;
}
@Override
public void run() {
house.consume(neednum);
}
}
测试用例
package day5;
/**
* <p>Title: Test.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2014</p>
* @author 雪含心
* @date 2014年2月7日
*/
public class Test {
public static void main(String[] args) {
Warehouse hourse = new Warehouse(30);
while(true){
Consumer c1 = new Consumer(hourse,50);
Consumer c2 = new Consumer(hourse, 20);
Consumer c3 = new Consumer(hourse, 30);
Consumer c4 = new Consumer(hourse,50);
Consumer c5 = new Consumer(hourse, 20);
Consumer c6 = new Consumer(hourse, 30);
Producer p1 = new Producer(hourse, 10);
Producer p2 = new Producer(hourse, 10);
Producer p3 = new Producer(hourse, 10);
Producer p4 = new Producer(hourse, 10);
Producer p5 = new Producer(hourse, 10);
Producer p6 = new Producer(hourse, 10);
Producer p7 = new Producer(hourse, 80);
c1.start();
c2.start();
c3.start();
c4.start();
c5.start();
c6.start();
p1.start();
p2.start();
p3.start();
p4.start();
p5.start();
p6.start();
p7.start();
}
}
}