java多线程– 信号灯法则

java
Author

dd21

Published

December 5, 2022

信号灯法则

利用标志位,控制生产和消费 生产一个消费一个

在这里插入图片描述
package cn.usts.edu.lesson08;
public class TrafficLightDemo {
    public static void main(String[] args) {
        Googs googs = new Googs();
        new Productor1(googs).start();
        new Consumer1(googs).start();
    }
}
//生产者
class Productor1 extends Thread{
    Googs goog;
    Productor1(Googs goog){
        this.goog = goog;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            goog.production(i+"产品");
        }
    }
}

//消费者
class Consumer1 extends Thread{
    Googs goog;
    Consumer1(Googs goog){
        this.goog = goog;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            goog.consume();
        }
    }
}

//商品
class Googs{
    //设置产品属性
    public String name;
    //设置标识位 flag为true消费者消费,如果false生产者生产
    boolean flag = true;

    //生产者生产
    public synchronized void production(String name){
        //如果生产完之后,等待消费者消费
        if(!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("生产者生产了第"+name);
        //通知消费者消费
        this.name = name;
        this.notifyAll();
        flag = !this.flag;
    }
    //消费者消费
    public synchronized void consume(){
        //如果消费完了,等待生产者生产
        if(flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("消费了"+this.name+"产品--");
        this.notifyAll();
        flag = !this.flag;

    }
}