使用阻塞队列可简化Java中生产者消费者模式的实现,确保线程安全;也可通过synchronized与wait/notify或Lock与Condition实现更细粒度控制,关键在于正确处理共享资源的同步与线程通信。

在Java中实现线程安全的生产者消费者模式,核心是协调多个线程对共享资源的访问,确保数据一致性并避免死锁、竞态条件等问题。通常使用阻塞队列或结合synchronized与wait/notify机制来完成。
示例代码:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;
<p>class Producer implements Runnable {
private final BlockingQueue<Integer> queue;</p><pre class='brush:java;toolbar:false;'>public Producer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
public void run() {
try {
for (int i = 1; i <= 10; i++) {
queue.put(i); // 自动阻塞
System.out.println("生产者生产: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}}
立即学习“Java免费学习笔记(深入)”;
class Consumer implements Runnable { private final BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
public void run() {
try {
while (true) {
Integer value = queue.take(); // 队列空时自动阻塞
System.out.println("消费者消费: " + value);
Thread.sleep(200);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}}
立即学习“Java免费学习笔记(深入)”;
public class ProducerConsumerExample { public static void main(String[] args) { BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5);
Thread producer = new Thread(new Producer(queue));
Thread consumer = new Thread(new Consumer(queue));
producer.start();
consumer.start();
}}
立即学习“Java免费学习笔记(深入)”;
优点:无需手动管理同步,put和take方法自动处理阻塞与唤醒,代码简洁且不易出错。
关键点:
示例代码片段:
class SharedBuffer {
private final int MAX_SIZE = 5;
private List<Integer> buffer = new ArrayList<>();
<pre class='brush:java;toolbar:false;'>public void produce(int item) throws InterruptedException {
synchronized (this) {
while (buffer.size() == MAX_SIZE) {
this.wait(); // 缓冲区满,生产者等待
}
buffer.add(item);
System.out.println("生产: " + item);
this.notifyAll(); // 唤醒消费者
}
}
public int consume() throws InterruptedException {
synchronized (this) {
while (buffer.isEmpty()) {
this.wait(); // 缓冲区空,消费者等待
}
int item = buffer.remove(buffer.size() - 1);
System.out.println("消费: " + item);
this.notifyAll(); // 唤醒生产者
return item;
}
}}
立即学习“Java免费学习笔记(深入)”;
注意:必须使用while循环检查条件,否则可能因虚假唤醒导致逻辑错误。
优势:
典型用法:
import java.util.concurrent.locks.*;
<p>class BufferWithCondition {
private final int[] buffer = new int[5];
private int count = 0, in = 0, out = 0;
private final Lock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();</p><pre class='brush:java;toolbar:false;'>public void put(int item) throws InterruptedException {
lock.lock();
try {
while (count == buffer.length) {
notFull.await(); // 等待非满
}
buffer[in] = item;
in = (in + 1) % buffer.length;
count++;
notEmpty.signal(); // 通知消费者
} finally {
lock.unlock();
}
}
public int take() throws InterruptedException {
lock.lock();
try {
while (count == 0) {
notEmpty.await(); // 等待非空
}
int item = buffer[out];
out = (out + 1) % buffer.length;
count--;
notFull.signal(); // 通知生产者
return item;
} finally {
lock.unlock();
}
}}
立即学习“Java免费学习笔记(深入)”;
这种方式比synchronized更灵活,适合复杂场景。
基本上就这些。选择哪种方式取决于需求:简单场景用阻塞队列最安全高效;需要定制逻辑可用synchronized+wait/notify或Lock+Condition。关键是保证共享状态的可见性与原子性,合理使用等待唤醒机制避免忙等。
以上就是Java里如何实现线程安全的生产者消费者模式_生产者消费者线程安全处理解析的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号