Implementing Producer-Consumer pattern using Java threads.
Jul 08, 2025 am 02:28 AM1. Using BlockingQueue is the most direct and recommended way to implement the Java producer-consumer model. It handles thread synchronization internally. The producer calls the put() method to block waiting queue space, and the consumer calls the take() method to block waiting data; 2. If the manual implementation requires the synchronized locking and wait/notify mechanism to coordinate thread behavior, the core is to loop check the conditions and operate the shared buffer within the synchronization block; 3. Notes include correct handling of interrupts, multi-threaded wake-up strategy to select notifyAll(), setting a reasonable buffer size, and elegantly closing threads.
In Java multithreaded programming, implementing the producer-consumer model is a common concurrency model. It is mainly used to solve the problem of collaboration between multiple threads: one or more threads are responsible for "production" of data, and another or more threads are responsible for "consuming" this data.

To implement this model, the key is how to safely pass data between threads and avoid resource competition and deadlock problems. Let’s start from several practical perspectives and talk about how to do it in detail.

Using BlockingQueue
is the most direct way
Java provides ready-made BlockingQueue
interfaces (such as ArrayBlockingQueue
or LinkedBlockingQueue
), which has handled thread synchronization problems internally and is the most recommended method for implementing producer-consumer.
It is very simple to use:

- The producer calls
put()
method to put data into the queue - The consumer calls
take()
method to retrieve data from the queue
Both methods are blocking, and when the queue is full, the producer will wait; when the queue is empty, the consumer will wait, which is exactly the same as our desired behavior.
Sample code snippet:
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10); // Producer thread new Thread(() -> { try { int i = 0; while (true) { queue.put(i); System.out.println("Produced: " i); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }).start(); // Consumer thread new Thread(() -> { try { while (true) { int value = queue.take(); System.out.println("Consumed: " value); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }).start();
If you do not use the ready-made queue, you can manually add lock control
If you don't want to rely on BlockingQueue
, you can also implement the logic manually. At this time, synchronized
keywords and wait/notify
mechanisms need to be used to coordinate thread behavior.
Core idea:
- Use a shared data structure (such as
List
) as a buffer - Locking when operating the buffer
- When the buffer is full, the producer thread waits; wakes up when there is space
- When the buffer is empty, the consumer thread waits; wakes up when new data is available
Notes:
- Conditions must be checked in the loop because there may be false wakeups
- Calling
wait()
andnotify()
must be done in the synchronization block
Example pseudocode:
public class SharedBuffer { private List<Integer> buffer = new ArrayList<>(); private final int MAX_SIZE = 10; public synchronized void put(int value) throws InterruptedException { while (buffer.size() == MAX_SIZE) { wait(); } buffer.add(value); notifyAll(); } public synchronized int take() throws InterruptedException { while (buffer.isEmpty()) { wait(); } int value = buffer.remove(0); notifyAll(); return value; } }
A few easy to ignore but important details
- Interrupt handling : The thread may be interrupted. Remember to capture
InterruptedException
and restore the interrupt state. - Wake-up strategy in multi-producer/consumer scenarios : If there are many threads waiting, try to use
notifyAll()
instead ofnotify()
to avoid missing wake-up - Setting a reasonable buffer size : Too large will waste memory, too small may lead to frequent waiting
- Elegantly close threads : loop exit can be controlled by adding flag bits instead of infinite loops not handling exit conditions
Basically that's it. BlockingQueue
can quickly implement functions, while manual implementation can help you understand the underlying mechanism. The two methods have their own applicable scenarios. By choosing the right tool, you can write a stable and efficient concurrent program.
The above is the detailed content of Implementing Producer-Consumer pattern using Java threads.. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In-depth understanding of the five states of Java threads and their conversion rules 1. Introduction to the five states of threads In Java, the life cycle of a thread can be divided into five different states, including new state (NEW), ready state (RUNNABLE), Running status (RUNNING), blocking status (BLOCKED) and termination status (TERMINATED). New state (NEW): When the thread object is created, it is in the new state. At this point, the thread object has allocated enough resources to perform the task

How to solve Java thread interrupt timeout exception (InterruptedTimeoutException) Introduction: In concurrent programming, thread interruption operation is a very common technical means. It can be used to terminate threads that no longer need to run, or to coordinate between multiple threads. However, sometimes thread interruption does not always complete smoothly, and interruption timeout may occur. This article will introduce how to solve the Java thread interrupt timeout exception (InterruptedTimeout

Java is a cross-platform programming language. Because of its advantages such as portability, ease of learning and ease of use, it has become an important player in the field of computer programming. However, thread safety has always been an important issue in Java programming. Thread safety issues in Java may not seem easy to detect on the surface, but they often lead to disturbing situations. This article will explore a thread safety issue in Java: java.lang.ThreadDeath. Thread safety issues in Java in multiple threads

How to solve the Java thread interrupt timeout error exception (ThreadInterruptedTimeoutErrorException). During the Java development process, we often use multi-threading to improve the concurrency performance and efficiency of the program. However, when using threads, we may encounter some problems, such as thread timeout error exception (ThreadInterruptedTimeoutErrorException). This article will explain how to solve this problem,

Methods to solve Java thread state exception (ThreadStateException) Introduction: When using Java multi-thread programming, you often encounter the problem of thread state exception (ThreadStateException). When we call certain methods of the thread, if the state of the thread does not meet the requirements of the method, a ThreadStateException will be thrown. This article will introduce the causes and solutions of thread status exceptions, and give relevant code examples.

How to solve the problem of Java thread interruption (ThreadInterrupted) Introduction: In Java multi-thread programming, thread interruption is a common problem. When one thread is waiting for or performing a task, we may want to interrupt another thread. However, thread interruption is not a simple matter and requires some skills and precautions. This article will explain how to solve the problem of Java thread interruption and provide some code examples. Understanding thread interrupts In Java, thread interrupts are a

Methods to solve Java inter-thread communication exception (ThreadCommunicationException) In Java programs, communication between threads is a very common requirement. However, due to the concurrent execution characteristics of threads, exceptions may occur in inter-thread communication, such as ThreadCommunicationException. This article will explore how to resolve this exception and give corresponding code examples. Exception background In multi-threaded programming, different threads need to share data or perform

Describe in detail the five states of Java threads and their characteristics and performance in a multi-threaded environment. Java is an object-oriented programming language. Its multi-threading characteristics allow us to perform multiple tasks at the same time and improve the concurrency and response of the program. sex. In Java, threads have five different states, namely new state (New), runnable state (Runnable), blocked state (Blocked), waiting state (Waiting) and terminated state (Terminated). This article will introduce this in detail
