答案:Java中实现线程安全队列可通过ConcurrentLinkedQueue、BlockingQueue、synchronized或ReentrantLock。ConcurrentLinkedQueue基于CAS实现高并发;BlockingQueue如ArrayBlockingQueue支持阻塞操作,适用于生产者-消费者模型;synchronized可手动同步LinkedList但性能较低;ReentrantLock结合Condition提供更灵活的等待通知机制,适合自定义队列。选择依据场景:高并发用ConcurrentLinkedQueue,需阻塞选BlockingQueue,定制化控制用ReentrantLock。

在Java中实现线程安全的队列操作,核心是保证多个线程同时访问队列时的数据一致性和操作原子性。可以通过使用内置的并发类、同步机制或显式锁来实现。下面介绍几种常见且有效的实现方式。
使用ConcurrentLinkedQueue(无锁线程安全队列)
ConcurrentLinkedQueue 是一个基于链表结构的无界线程安全队列,采用非阻塞算法(CAS操作)实现高并发性能。
- 适合高读写并发场景,不会阻塞线程
- 不支持阻塞操作(如等待元素入队)
- 提供 add()、offer()、poll()、peek() 等线程安全方法
示例代码:
ConcurrentLinkedQueuequeue = new ConcurrentLinkedQueue<>(); queue.offer("item1"); String item = queue.poll(); // 线程安全
使用BlockingQueue阻塞队列
Java 提供了 BlockingQueue 接口及多个实现类,适用于生产者-消费者模型,自动处理线程阻塞与唤醒。
立即学习“Java免费学习笔记(深入)”;
- ArrayBlockingQueue:有界队列,基于数组实现,需指定容量
- LinkedBlockingQueue:可选有界/无界,基于链表,吞吐量通常更高
- PriorityBlockingQueue:支持优先级排序的无界阻塞队列
这些实现内部已通过锁机制(如 ReentrantLock)确保线程安全,开发者无需额外同步。
示例代码:
BlockingQueuequeue = new ArrayBlockingQueue<>(10); new Thread(() -> { try { queue.put("msg"); // 队列满时自动阻塞 } catch (InterruptedException e) { } }).start(); new Thread(() -> { try { String msg = queue.take(); // 队列空时自动阻塞 System.out.println(msg); } catch (InterruptedException e) { } }).start();
使用synchronized关键字手动同步
如果使用普通集合(如 LinkedList),需要手动加锁来保证线程安全。
- 使用 synchronized 方法或代码块保护入队和出队操作
- 适合自定义队列逻辑或学习目的
- 性能低于并发包中的专用类
示例代码:
public class SafeQueue{ private final LinkedList list = new LinkedList<>(); public synchronized void enqueue(T item) { list.addLast(item); notify(); // 唤醒等待的出队线程 } public synchronized T dequeue() throws InterruptedException { while (list.isEmpty()) { wait(); // 队列为空时等待 } return list.removeFirst(); } }
使用ReentrantLock + Condition提升灵活性
相比 synchronized,ReentrantLock 提供更细粒度的控制,结合 Condition 可实现高效等待/通知机制。
优势包括:可中断等待、超时尝试获取、公平锁选项等。
public class LockBasedQueue{ private final LinkedList list = new LinkedList<>(); private final ReentrantLock lock = new ReentrantLock(); private final Condition notEmpty = lock.newCondition(); private final Condition notFull = lock.newCondition(); private final int capacity; public LockBasedQueue(int capacity) { this.capacity = capacity; } public void put(T item) throws InterruptedException { lock.lock(); try { while (list.size() == capacity) { notFull.await(); } list.addLast(item); notEmpty.signal(); } finally { lock.unlock(); } } public T take() throws InterruptedException { lock.lock(); try { while (list.isEmpty()) { notEmpty.await(); } T item = list.removeFirst(); notFull.signal(); return item; } finally { lock.unlock(); } } }
基本上就这些。选择哪种方式取决于具体需求:高并发推荐 ConcurrentLinkedQueue 或 BlockingQueue;需要阻塞特性优先使用 BlockingQueue 实现;自定义逻辑可考虑 ReentrantLock。避免使用 synchronized + 手动 wait/notify,除非理解其细节。正确使用 JDK 并发工具类能大幅降低出错概率。










