多线程基础-生产者消费者问题

2024/06/20 Java
public class BaoZiPu {

    public int count = 0;

    private boolean flag = false;

    public BaoZiPu(int count, boolean flag) {
        this.count = count;
        this.flag = flag;
    }

    public BaoZiPu() {
    }

    public synchronized int getCount() {
        while (!this.flag) {
            // 没有包子就等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        System.out.println("消费第...." + count + "个包子.");
        flag = false;
        this.notifyAll();
        return count;
    }

    public synchronized void setCount() {
        while (this.flag) {
            // 有包子不用生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        count++;
        System.out.println("生产第" + count + "个包子.");
        this.flag = true;
        this.notifyAll();
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}

public class Consume implements Runnable {
    private BaoZiPu baoZiPu;

    public Consume(BaoZiPu baoZiPu) {
        this.baoZiPu = baoZiPu;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            baoZiPu.getCount();
        }
    }
}

public class Product implements Runnable {

    private BaoZiPu baoZiPu;

    public Product(BaoZiPu baoZiPu) {
        this.baoZiPu = baoZiPu;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            baoZiPu.setCount();
        }
    }
}


public class TestMain {

    public static void main(String[] args) {
        BaoZiPu baoZiPu = new BaoZiPu();
        Product product = new Product(baoZiPu);
        Consume consume = new Consume(baoZiPu);


        new Thread(product).start();
        new Thread(product).start();
        new Thread(product).start();

        new Thread(consume).start();
        new Thread(consume).start();
        new Thread(consume).start();
    }
}

Search

    Table of Contents