Java多线程- 生产者消费者

package per.mjn.bean;

import java.util.LinkedList;

import static java.lang.Thread.sleep;

class Message {
    private int id;
    private Object value;

    public int getId() {
        return id;
    }

    public Object getValue() {
        return value;
    }

    public Message(int id, Object value) {
        this.id = id;
        this.value = value;
    }

    @Override
    public String toString() {
        return "Message{" +
                "id=" + id +
                ", value=" + value +
                '}';
    }
}

class MessageQueue {
    private LinkedList<Message> list = new LinkedList<>();
    private int capacity;

    public MessageQueue(int capacity) {
        this.capacity = capacity;
    }

    public Message take() {
        synchronized (list) {
            while (list.isEmpty()) {
                try {
                    System.out.println("队列为空,消费者线程【" + Thread.currentThread().getName() + "】等待");
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Message message = list.removeFirst();
            System.out.println(Thread.currentThread().getName() + "已消费一个消息" + message);
            list.notifyAll();
            return message;
        }
    }

    public void put(Message message) {
        synchronized (list) {
            while (list.size() == capacity) {
                try {
                    System.out.println("队列已满,生产者线程【" + Thread.currentThread().getName() + "】等待");
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.add(message);
            System.out.println(Thread.currentThread().getName() + "已生产一个消息" + message);
            list.notifyAll();
        }
    }
}

public class Test {
    public static void main(String[] args) {
        MessageQueue queue = new MessageQueue(2);

        for (int i = 0; i < 3; ++i) {
            int id = i;
            new Thread(() -> {
                Message message = new Message(id, "值" + id);
                queue.put(message);
            }, "生产者" + i).start();
        }

        new Thread(() -> {
            while (true) {
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message message = queue.take();
            }
        }, "消费者").start();
    }
}

程序输出结果如下:

生产者2已生产一个消息Message{id=2, value=2}
生产者1已生产一个消息Message{id=1, value=1}
队列已满,生产者线程【生产者0】等待
消费者已消费一个消息Message{id=2, value=2}
生产者0已生产一个消息Message{id=0, value=0}
消费者已消费一个消息Message{id=1, value=1}
消费者已消费一个消息Message{id=0, value=0}
队列为空,消费者线程【消费者】等待

你可能感兴趣的:(Java基础,java,python)