生产者和消费者模型

public class Main {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Thread producer = new Thread(new Producer(clerk));
        Thread consumer = new Thread(new Consumer(clerk));
        Thread consumer2 = new Thread(new Consumer(clerk));
        producer.start();
        consumer.start();
        consumer2.start();

    }
}


class Clerk {
    private int productNumber = 0;

    public synchronized void produceProduct() {
        if (productNumber < 20) {
            productNumber++;
            System.out.println(Thread.currentThread().getName() + ":开始生产第" + productNumber + "个产品");
            notify();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void consumeProduct() {
        if (productNumber > 0) {
            System.out.println(Thread.currentThread().getName() + ":开始消费第" + productNumber + "个产品");
            productNumber--;
            notify();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


class Producer implements Runnable {
    Clerk clerk;

    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.produceProduct();
        }

    }
}

class Consumer implements Runnable {
    Clerk clerk;

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.consumeProduct();
        }
    }

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }


}
posted @ 2022-03-19 19:53  诗酒  阅读(61)  评论(0编辑  收藏  举报