一、模拟仓库
package 生产者消费者;
import java.util.LinkedList;
/*
* 1.模拟仓库类
* */
public class Storage {
// 定义最大存储量
private final int MAX_SIZE = 100;
// 定义列表存储商品
private LinkedList<Object> list = new LinkedList<Object>();
// 生产num个商品
synchronized public void produce(int num) {
while (list.size() + num > MAX_SIZE) {
System.out.println("【要生产的产品数】:" + num + "\t库存量:" + list.size()
+ "暂时不能执行生产任务 ");
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 1; i <= num; i++) {
list.add(new Object());
}
System.out.println("【已经生产产品数】:" + num + "\t【现仓储为】:" + list.size());
this.notifyAll();
}
// 消费num个商品
synchronized public void consumer(int num) {
while (list.size() < num) {
System.out.println("【要消费的产品数量】:" + num + "\t【库存量】:" + list.size()
+ "\t暂时不能执行消费任务!");
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 1; i <= num; i++) {
list.remove();
}
System.out.println("【已经消费产品数】:" + num + "\t【现仓储量为】:" + list.size());
this.notifyAll();
}
}
二、模拟生产者
package 生产者消费者;
public class Producer extends Thread {
private Storage storage;
private int num;
public Producer(Storage storage, int num) {
super();
this.storage = storage;
this.num = num;
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
storage.produce(num);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
三、模拟消费者
package 生产者消费者;
public class Consumer extends Thread {
private Storage storage;
private int num;
public Consumer(Storage storage, int num) {
super();
this.storage = storage;
this.num = num;
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
storage.consumer(num);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
四、测试
package 生产者消费者;
public class Test {
public static void main(String[] args) {
Storage storage = new Storage();
Producer p1 = new Producer(storage, 2);
Producer p2 = new Producer(storage, 4);
Producer p3 = new Producer(storage, 6);
Producer p4 = new Producer(storage, 8);
Producer p5 = new Producer(storage, 10);
Consumer c1 = new Consumer(storage, 1);
Consumer c2 = new Consumer(storage, 3);
Consumer c3 = new Consumer(storage, 5);
Consumer c4 = new Consumer(storage, 7);
Consumer c5 = new Consumer(storage, 9);
p1.start();
p2.start();
p3.start();
p4.start();
p5.start();
c1.start();
c2.start();
c3.start();
c4.start();
c5.start();
}
}