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

生产者-消费者问题是经典的多线程同步问题,可以使用 Java 中的 wait()notify() 或者 notifyAll() 方法来实现。下面是一个简单的示例代码,演示了如何使用 wait()notify() 方法来解决生产者-消费者问题:

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

public class ProducerConsumerExample {

    public static void main(String[] args) {
        final int CAPACITY = 5;
        Queue<Integer> queue = new LinkedList<>();

        Thread producer = new Thread(new Producer(queue, CAPACITY), "Producer");
        Thread consumer = new Thread(new Consumer(queue), "Consumer");

        producer.start();
        consumer.start();
    }

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

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

        @Override
        public void run() {
            int value = 0;
            while (true) {
                synchronized (queue) {
                    try {
                        while (queue.size() == capacity) {
                            System.out.println("Queue is full, Producer is waiting...");
                            queue.wait();
                        }

                        System.out.println("Producer produced: " + value);
                        queue.offer(value++);
                        queue.notifyAll();

                        Thread.sleep(1000); // 模拟生产过程

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

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

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

        @Override
        public void run() {
            while (true) {
                synchronized (queue) {
                    try {
                        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();

                        Thread.sleep(1500); // 模拟消费过程

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

解释说明:

  1. Queue 定义: 使用 LinkedList 实现 Queue,用于存储生产者和消费者共享的数据。

  2. Producer 类:

    • run() 方法中使用 synchronized 关键字锁住 queue 对象,确保多个生产者线程互斥访问。
    • 如果队列满了 (queue.size() == capacity),则生产者线程调用 queue.wait() 进入等待状态,直到消费者消费数据并唤醒生产者。
    • 生产者生产数据 (queue.offer(value++)),并使用 queue.notifyAll() 唤醒所有等待的消费者线程。
  3. Consumer 类:

    • run() 方法中同样使用 synchronized 关键字锁住 queue 对象。
    • 如果队列为空 (queue.isEmpty()),则消费者线程调用 queue.wait() 进入等待状态,直到生产者生产数据并唤醒消费者。
    • 消费者消费数据 (queue.poll()),并使用 queue.notifyAll() 唤醒所有等待的生产者线程。
  4. 注意事项:

    • 使用 wait()notify() 方法时,必须在同步代码块中使用,并且必须持有对象的锁(即使用 synchronized)。
    • notify() 方法唤醒一个等待的线程,而 notifyAll() 方法唤醒所有等待的线程,具体使用哪个取决于需求。
    • 生产者和消费者通过共享的队列来进行数据交换,通过 wait()notify() 方法来进行线程间的通信和同步。

以上代码演示了基本的生产者-消费者模型的实现方式,可以根据具体的需求和场景进行适当调整和扩展。

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是使用Java实现生产者-消费者(仓库)程序的代码: ```java import java.util.LinkedList; public class ProducerConsumerExample { public static void main(String[] args) { final PC pc = new PC(); // 创建生产者线程 Thread t1 = new Thread(new Runnable() { @Override public void run() { try { pc.produce(); } catch (InterruptedException e) { e.printStackTrace(); } } }); // 创建消费者线程 Thread t2 = new Thread(new Runnable() { @Override public void run() { try { pc.consume(); } catch (InterruptedException e) { e.printStackTrace(); } } }); // 启动线程 t1.start(); t2.start(); // 等待线程结束 try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } } // 仓库类 public static class PC { // 仓库大小 private final int CAPACITY = 10; // 用于存放产品的仓库 private final LinkedList<Integer> queue = new LinkedList<>(); // 生产者 public void produce() throws InterruptedException { int value = 0; while (true) { synchronized (this) { // 如果仓库已满,则等待 while (queue.size() == CAPACITY) { wait(); } System.out.println("生产者生产: " + value); // 生产产品并放入仓库 queue.add(value++); // 唤醒消费者线程 notify(); // 休眠一段时间 Thread.sleep(1000); } } } // 消费者 public void consume() throws InterruptedException { while (true) { synchronized (this) { // 如果仓库为空,则等待 while (queue.size() == 0) { wait(); } // 从仓库取出产品 int value = queue.removeFirst(); System.out.println("消费者消费: " + value); // 唤醒生产者线程 notify(); // 休眠一段时间 Thread.sleep(1000); } } } } } ``` 在上面的代码,我们使用了一个`LinkedList`来模拟仓库,其`CAPACITY`表示仓库的大小,`queue`表示存放产品的队列。`produce()`方法用于生产产品,`consume()`方法用于消费产品。在生产和消费产品时,我们使用`synchronized`来保证线程同步,使用`wait()`和`notify()`来控制线程的运行。在生产产品时,如果仓库已满,则生产者线程将等待;在消费产品时,如果仓库为空,则消费者线程将等待。这样就实现了生产者-消费者(仓库)程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

伟主教

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值