Java多线程生产者消费者模型

 

用多线程实现一个生产者消费者模型,满足如下条件:

1. 先生产后消费,不生产不消费

2. 要求最多生产5个产品,超过5个则不能继续生产,低于0个则不能消费

3. 采用多线程实现

 

相关Java程序如下。

 

package cn.edu.lcudcc;

import java.util.LinkedList;
import java.util.Queue;

public class ProducerConsumer {
    private static final int MAX_SIZE = 5;
    private final Queue<Integer> queue = new LinkedList<>();

    class Producer extends Thread {
        @Override
        public void run() {
            int value = 0;
            while (true) {
                synchronized (queue) {
                    while (queue.size() >= MAX_SIZE) {
                        try {
                            System.out.println("队列满,生产者 " + Thread.currentThread().getName() + " 等待");
                            queue.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("生产者 " + Thread.currentThread().getName() + " 生产了产品:" + value);
                    queue.offer(value++);
                    queue.notifyAll();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    class Consumer extends Thread {
        @Override
        public void run() {
            while (true) {
                synchronized (queue) {
                    while (queue.isEmpty()) {
                        try {
                            System.out.println("队列空,消费者 " + Thread.currentThread().getName() + " 等待");
                            queue.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    int value = queue.poll();
                    System.out.println("消费者 " + Thread.currentThread().getName() + " 消费了产品:" + value);
                    queue.notifyAll();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        ProducerConsumer pc = new ProducerConsumer();
        pc.new Producer().start();
        pc.new Consumer().start();
    }
}

 

posted @ 2023-11-22 08:53  宝山方圆  阅读(8)  评论(0编辑  收藏  举报