标签:rup 消费者 生产 test class lan code 不能 stp
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
//生产者
class Productor extends Thread{
SynContainer synContainer;
public Productor(SynContainer synContainer){
this.synContainer = synContainer;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
synContainer.push(new Chicken(i));
System.out.println("生产者生产了第" + i +"只鸡");
}
}
}
//消费者
class Consumer extends Thread{
SynContainer synContainer;
public Consumer(SynContainer synContainer){
this.synContainer = synContainer;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费者消费了第" + synContainer.pop().num +"只鸡");
}
}
}
//产品
class Chicken{
int num;//产品编号
public Chicken(int num) {
this.num = num;
}
}
//缓冲区
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.notifyAll();
}
//消费者消费产品
public synchronized Chicken pop(){
if (count == 0){
//通知生产者生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
Chicken chicken = chickens[count];
//通知生产者可以生产
this.notifyAll();
return chicken;
}
}
标签:rup 消费者 生产 test class lan code 不能 stp
原文地址:https://www.cnblogs.com/xd-study/p/13195831.html