酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

java实现 利用多线程模拟生产消费模式,生产者负责生产商品,消费者负责购买,假设有两个生产者,三个消费者,生产者负责生产商品,消费者负责购买如果商品数量为0,则消费者暂停购买,知道有商品了才继续,每个生产者最多可生产10个商品。

```java public class ProducerConsumer { static int numProducts = 0; static final int MAX_PRODUCTS = 10; public static void main(String[] args) { Thread[] producers = new Thread[2]; Thread[] consumers = new Thread[3]; for (int i = 0; i < producers.length; i++) { producers[i] = new Thread(new ProducerThread(), "Producer-" + i); producers[i].start(); } for (int i = 0; i < consumers.length; i++) { consumers[i] = new Thread(new ConsumerThread(), "Consumer-" + i); consumers[i].start(); } } static class ProducerThread implements Runnable { @Override public void run() { while (true) { synchronized (this) { try { if (numProducts >= MAX_PRODUCTS) { wait(); } else { numProducts++; System.out.println(Thread.currentThread().getName() + " produced a product. Total products: " + numProducts); notifyAll(); } } catch (InterruptedException e) { e.printStackTrace(); } } } } } static class ConsumerThread implements Runnable { @Override public void run() { while (true) { synchronized (this) { try { if (numProducts == 0) { wait(); } else { numProducts--; System.out.println(Thread.currentThread().getName() + " bought a product. Total products: " + numProducts); notifyAll(); } } catch (InterruptedException e) { e.printStackTrace(); } } } } } } ``` 这段代码中,我们创建了两个生产者线程和三个消费者线程。生产者线程的任务是生产商品,消费者线程的任务是购买商品。当商品数量达到上限时,生产者线程暂停生产,直到有商品被消费后才继续生产。当商品数量为0时,消费者线程暂停购买,直到有商品被生产后才继续购买。 在生产者线程中,我们使用`synchronized`关键字来保证线程安全,确保商品数量的操作是原子性的。在达到条件时,我们调用`wait()`方法来暂停线程,并通过`notifyAll()`方法唤醒其他等待的线程。 在消费者线程中也是同样的逻辑,确保线程安全并实现暂停和唤醒的功能。 通过以上代码,我们可以模拟生产消费模式,实现多个生产者和消费者之间的合作。 [2024-11-27 08:37:19 | AI写代码神器 | 1789点数解答]

相关提问