多线程生产者消费者模型

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

public class test {
    public static void main(String[] args) {
        Storage storage = new Storage();

        // 创建3个生产者和2个消费者
        for (int i = 0; i < 3; i++) {
            new Producer("Producer-" + i, storage).start();
        }

        for (int i = 0; i < 2; i++) {
            new Consumer("Consumer-" + i, storage).start();
        }
    }
}

class Storage {
    private final Queue<Object> items = new LinkedList<>();
    private final int MAX_SIZE = 10;
    private Integer item=0;

    public synchronized void put() throws InterruptedException {
        // 使用while防止虚假唤醒
        while (items.size() >= MAX_SIZE) {
            wait();
        }
        item = item+1; // 生产一个新对象
        items.offer(item);
        System.out.println(Thread.currentThread().getName() + " put " +item.toString()+ ", current size: " + items.size());
        notifyAll(); // 唤醒所有等待线程
    }

    public synchronized Object take() throws InterruptedException {
        while (items.isEmpty()) {
            wait();
        }
        Object item = items.poll();
        System.out.println(Thread.currentThread().getName() + " take "+item.toString()+", current size: " + items.size());
        notifyAll(); // 唤醒所有等待线程
        return item;
    }
}

class Producer extends Thread {
    private final Storage storage;

    public Producer(String name, Storage storage) {
        super(name);
        this.storage = storage;
    }

    @Override
    public void run() {
        try {
            while (true) {
                storage.put();
                Thread.sleep((long) (Math.random() * 1000)); // 模拟生产耗时
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

class Consumer extends Thread {
    private final Storage storage;

    public Consumer(String name, Storage storage) {
        super(name);
        this.storage = storage;
    }

    @Override
    public void run() {
        try {
            while (true) {
                storage.take();
                Thread.sleep((long) (Math.random() * 1000)); // 模拟消费耗时
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
		
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值