测试:生产者消费者模型–》利用缓冲区解决:管程法
生产者,消费者,产品,缓冲
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
//使用多线程的方式进行模拟
// Productor productor = new Productor(container);
// Consumer consumer1 = new Consumer(container);
// Consumer consumer2 = new Consumer(container);
// Consumer consumer3 = new Consumer(container);
// Thread thread = new Thread(productor, "工人A");
// Thread thread1 = new Thread(consumer1, "张三");
// Thread thread2 = new Thread(consumer2, "李四");
// Thread thread3 = new Thread(consumer3, "王五");
// thread.start();
// thread1.start();
// thread2.start();
// thread3.start();
//使用线程池
ExecutorService service = Executors.newFixedThreadPool(10);
service.execute(new Productor(container));
service.execute(new Productor(container));
service.execute(new Consumer(container));
service.execute(new Consumer(container));
service.execute(new Consumer(container));
service.shutdown();
}
}
//生产者
class Productor implements Runnable {
SynContainer container;
public Productor(SynContainer container) {
this.container = container;
}
//定时生成鸡
@Override
public void run() {
for (int i = 0; i < 100; i++) {
// try {
// Thread.sleep(50);
// } catch (InterruptedException e) {
// throw new RuntimeException(e);
// }
System.out.println(Thread.currentThread().getName() + "生产了" + i + "只鸡");
container.push(new Chicken(i));
}
System.out.println(Thread.currentThread().getName() +"工厂生产完毕!");
}
}
//消费者
class Consumer implements Runnable {
SynContainer container;
int count = 0;
public Consumer(SynContainer container) {
this.container = container;
}
@Override
public void run() {
while (true) {
count++;
System.out.println(Thread.currentThread().getName() + "消费了--》第" + container.pop().id + "只鸡,共消费了"+count+"只");
}
}
}
//产品
class Chicken {
int id;
public Chicken(int id) {
this.id = id;
}
}
//缓存区
//方法有存放,取出
class SynContainer {
//容器大小
Chicken[] chickens = new Chicken[10];
//容器计数器
int count = 0;
//生产者放入产品
public synchronized void push(Chicken chicken) {
//如果容器满了,就需要等待消费者消费
if (count >= chickens.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满,则需要丢入产品
chickens[count] = chicken;
count++;
//通知消费者可以消费;
this.notify();
}
//消费者消费鸡
public synchronized Chicken pop() {
while (count == 0) {
//等待生产者生产
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//如果可以消费
count--;
Chicken chicken = chickens[count];
//通知生产者生产
this.notifyAll();
return chicken;
}
}