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.
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:
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!