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

发布时间 2023-09-08 20:13:08作者: 被占用的小海海
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();
        }
    }
}