26 生产者消费者问题:利用标志位:信号灯法

package ThreadDemo;

//  生产者消费者问题:利用标志位:信号灯法,只对缓冲区容量为一个的有效?
public class Test26_Producer_Consumer_2 {
    public static void main(String[] args) {
        PC pc = new PC();
        new P(pc).start();
        new C(pc).start();

    }
}

class P extends Thread{
    PC pc;
    public P(PC pc){
        this.pc=pc;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                pc.push();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

class C extends Thread{
    PC pc;
    public C(PC pc){
        this.pc=pc;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                pc.pop();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}


class PC{
    boolean flag=true;  // T:生产者生产,消费者等待;F:消费者消费,生产者等待

    public synchronized void push() throws InterruptedException {
        if (!flag){
            wait();
        }
        if (flag){
            System.out.println("生产者生产产品");
            flag=!flag;
            notify();
        }
    }
    public synchronized void pop() throws InterruptedException {
        if (flag){
            wait();
        }
        if (!flag){
            System.out.println("消费者消费产品");
            flag=!flag;
            notify();
        }
    }
}
posted @   被占用的小海海  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示