Home  >  Article  >  Java  >  How to implement producer-consumer model using blocking queue in Java?

How to implement producer-consumer model using blocking queue in Java?

王林
王林Original
2024-05-03 15:03:01268browse

The blocking queue in Java is used to implement the producer-consumer model: producer threads add data to the queue, and consumer threads read data from the queue. When the queue is full, the producer blocks until space is available; when the queue is empty, the consumer blocks until data is available to read. Practical cases: concurrency issues such as caching systems, message queues, and pipeline processing.

如何在 Java 中使用阻塞队列实现生产者消费者模型?

Use blocking queue to implement the producer-consumer model in Java

The blocking queue is a thread-safe data structure. It helps us achieve synchronization between producers and consumers. Producer threads add data to the queue, while consumer threads read data from the queue. If the queue is full, the producer blocks until space becomes available. If the queue is empty, the consumer blocks until data is available to read.

Sample code:

Producer.java

import java.util.concurrent.BlockingQueue;

public class Producer implements Runnable {

    private BlockingQueue<Integer> queue;

    public Producer(BlockingQueue<Integer> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                queue.put(i);
                System.out.println("Produced: " + i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Consumer.java

import java.util.concurrent.BlockingQueue;

public class Consumer implements Runnable {

    private BlockingQueue<Integer> queue;

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

    @Override
    public void run() {
        while (true) {
            try {
                Integer item = queue.take();
                System.out.println("Consumed: " + item);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Main.java

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {

    public static void main(String[] args) {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);

        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(producer);
        executorService.submit(consumer);

        executorService.shutdown();
    }
}

Practical case:

This model can be used to solve a variety of concurrency problems, such as:

  • In the cache system, the producer thread generates data, and the consumer thread consumes the data.
  • In a message queue system, producer threads publish messages, and consumer threads process messages.
  • In pipeline processing, the producer thread generates intermediate data, while the consumer thread processes the intermediate data and generates the final result.

The above is the detailed content of How to implement producer-consumer model using blocking queue in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn