用 wait-notify 写一段代码来解决生产者-消费者问题?

下面是使用waitnotify解决生产者-消费者问题的示例代码:

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

class Producer implements Runnable {
    private final Queue<Integer> queue;
    private final int maxSize;

    public Producer(Queue<Integer> queue, int maxSize) {
        this.queue = queue;
        this.maxSize = maxSize;
    }

    @Override
    public void run() {
        int i = 0;
        while (true) {
            try {
                produce(i++);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void produce(int i) throws InterruptedException {
        synchronized (queue) {
            while (queue.size() == maxSize) {
                System.out.println("Queue is full, producer is waiting...");
                queue.wait();
            }
            queue.add(i);
            System.out.println("Producer produced: " + i);
            queue.notifyAll();
        }
    }
}

class Consumer implements Runnable {
    private final Queue<Integer> queue;

    public Consumer(Queue<Integer> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                consume();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void consume() throws InterruptedException {
        synchronized (queue) {
            while (queue.isEmpty()) {
                System.out.println("Queue is empty, consumer is waiting...");
                queue.wait();
            }
            int value = queue.poll();
            System.out.println("Consumer consumed: " + value);
            queue.notifyAll();
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList<>();
        int maxSize = 5;
        
        Producer producer = new Producer(queue, maxSize);
        Consumer consumer = new Consumer(queue);
        
        Thread producerThread = new Thread(producer);
        Thread consumerThread = new Thread(consumer);
        
        producerThread.start();
        consumerThread.start();
    }
}

该代码中创建了一个大小为maxSize的队列,并分别创建了生产者Producer和消费者Consumer实例。生产者线程不断向队列中添加元素,而消费者线程不断从队列中消费元素。如果队列已满,生产者线程进入等待状态,直到队列有空闲位置。如果队列为空,消费者线程进入等待状态,直到队列中有元素。当生产者向队列中添加元素或消费者从队列中消费元素时,会使用wait方法使线程进入等待状态,并使用notifyAll方法唤醒等待的线程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值