代码注释就明白大概了,操作系统才能讲明白
//测试生产者消费者,---》利用缓存区,和管程
public class TestPC {
public static void main(String[] args) {
SynContainer container=new SynContainer();
new Producer(container).start();
new Consumer(container).start();
}
}
//生产者
class Producer extends Thread{
SynContainer synContainer;
public Producer(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().id+"只鸡");
}
}
}
//产品
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){
//如果容器满了
while(count==10){
//等待,通知消费者消费
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//没满丢入商品
chickens[count++]=chicken;
//通知消费者消费
this.notifyAll();
}
//消费者消费产品
public synchronized Chicken pop(){
//判断是否消费
while (count==0){
//等待生产者生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//可以消费
count--;
Chicken chicken=chickens[count];
//通知生产者快生产
this.notifyAll();
return chicken;
}
}
本文通过Java代码实现生产者消费者模式,使用缓存区和管程解决同步问题。生产者不断生产产品,消费者消费产品,两者通过缓存区进行协调,确保生产和消费的顺利进行。
478

被折叠的 条评论
为什么被折叠?



