答案:Java中实现线程安全单向队列的主要方式包括使用ConcurrentLinkedQueue实现无锁高性能非阻塞队列,BlockingQueue接口的LinkedBlockingQueue或ArrayBlockingQueue实现支持阻塞的有界或无界队列,通过synchronized关键字对LinkedList进行手动同步,以及使用ReentrantLock与Condition实现更灵活的锁控制;推荐优先选用BlockingQueue实现类以兼顾安全性与开发效率。
在Java中实现线程安全的单向队列,核心目标是确保多个线程同时进行入队和出队操作时,不会出现数据不一致、竞态条件或并发异常。以下是几种常见且有效的实现方式。
它采用CAS(Compare and Swap)操作保证线程安全,性能较高,但不支持阻塞操作。
示例代码:
import java.util.concurrent.ConcurrentLinkedQueue; ConcurrentLinkedQueuequeue = new ConcurrentLinkedQueue<>(); queue.offer("item1"); // 入队 String item = queue.poll(); // 出队,无元素时返回null
适用于不需要阻塞等待、追求高性能的非阻塞队列场景。
当队列为空时,消费者线程会自动阻塞;当队列满时,生产者线程也会阻塞(仅限有界队列)。
典型用法:
示例代码:
import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; BlockingQueuequeue = new LinkedBlockingQueue<>(10); queue.put("item1"); // 入队,队列满时阻塞 String item = queue.take(); // 出队,队列空时阻塞
适合需要线程间协调、支持阻塞操作的场景。
这种方式灵活但性能低于并发包中的专用类,仅建议在特殊需求下使用。
示例代码:
import java.util.LinkedList; public class ThreadSafeQueue{ private final LinkedList list = new LinkedList<>(); public synchronized void enqueue(T item) { list.addLast(item); notifyAll(); // 唤醒等待的出队线程 } public synchronized T dequeue() throws InterruptedException { while (list.isEmpty()) { wait(); // 队列为空时等待 } return list.removeFirst(); } }
注意手动管理wait/notify机制,确保线程正确唤醒。
适用于对锁行为有更高控制需求的场景。
示例代码片段:
import java.util.LinkedList; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.Condition; public class SafeQueue{ private final LinkedList list = new LinkedList<>(); private final ReentrantLock lock = new ReentrantLock(); private final Condition notEmpty = lock.newCondition(); public void enqueue(T item) { lock.lock(); try { list.addLast(item); notEmpty.signal(); // 通知等待的出队线程 } finally { lock.unlock(); } } public T dequeue() throws InterruptedException { lock.lock(); try { while (list.isEmpty()) { notEmpty.await(); } return list.removeFirst(); } finally { lock.unlock(); } } }
基本上就这些常见的线程安全单向队列实现方式。根据是否需要阻塞、性能要求和边界控制,选择合适的方法即可。推荐优先使用BlockingQueue的实现类,兼顾安全性和开发效率。