Java Queue队列如何实现线程安全

2025-03-21日常编程296313

在Java中,要实现线程安全的队列,可以使用以下几种方法:

  1. 使用java.util.concurrent包中的线程安全队列类:

    Java提供了许多线程安全的队列类,如ConcurrentLinkedQueueLinkedBlockingQueueArrayBlockingQueue等。这些类已经实现了线程安全,可以直接使用。

    例如,使用LinkedBlockingQueue

    import java.util.concurrent.LinkedBlockingQueue;
    
    public class Main {
        public static void main(String[] args) {
            LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
    
            // 生产者线程
            Thread producer = new Thread(() -> {
                for (int i = 0; i < 10; i++) {
                    try {
                        queue.put("Element " + i);
                        System.out.println("Produced: Element " + i);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
    
            // 消费者线程
            Thread consumer = new Thread(() -> {
                for (int i = 0; i < 10; i++) {
                    try {
                        String element = queue.take();
                        System.out.println("Consumed: " + element);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
    
            producer.start();
            consumer.start();
        }
    }
    
  2. 使用synchronized关键字:

    如果你使用的是非线程安全的队列类(如LinkedList),可以通过在操作队列的方法上添加synchronized关键字来实现线程安全。

    例如:

    import java.util.LinkedList;
    import java.util.Queue;
    
    public class Main {
        private static Queue<String> queue = new LinkedList<>();
    
        public static synchronized void enqueue(String element) {
            queue.add(element);
        }
    
        public static synchronized String dequeue() {
            return queue.poll();
        }
    
        public static void main(String[] args) {
            // 生产者线程
            Thread producer = new Thread(() -> {
                for (int i = 0; i < 10; i++) {
                    enqueue("Element " + i);
                    System.out.println("Produced: Element " + i);
                }
            });
    
            // 消费者线程
            Thread consumer = new Thread(() -> {
                for (int i = 0; i < 10; i++) {
                    String element = dequeue();
                    System.out.println("Consumed: " + element);
                }
            });
    
            producer.start();
            consumer.start();
        }
    }
    
  3. 使用ReentrantLockCondition

    另一种实现线程安全队列的方法是使用ReentrantLockCondition。这种方法提供了更灵活的锁定机制,可以在特定条件下等待或通知其他线程。

    例如:

    import java.util.LinkedList;
    import java.util.Queue;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class Main {
        private static Queue<String> queue = new LinkedList<>();
        private static Lock lock = new ReentrantLock();
        private static Condition notEmpty = lock.newCondition();
        private static Condition notFull = lock.newCondition();
        private static final int MAX_SIZE = 10;
    
        public static void enqueue(String element) throws InterruptedException {
            lock.lock();
            try {
                while (queue.size() == MAX_SIZE) {
                    notFull.await();
                }
                queue.add(element);
                notEmpty.signalAll();
            } finally {
                lock.unlock();
            }
        }
    
        public static String dequeue() throws InterruptedException {
            lock.lock();
            try {
                while (queue.isEmpty()) {
                    notEmpty.await();
                }
                String element = queue.poll();
                notFull.signalAll();
                return element;
            } finally {
                lock.unlock();
            }
        }
    
        public static void main(String[] args) {
            // 生产者线程
            Thread producer = new Thread(() -> {
                for (int i = 0; i < 10; i++) {
                    try {
                        enqueue("Element " + i);
                        System.out.println("Produced: Element " + i);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
    
            // 消费者线程
            Thread consumer = new Thread(() -> {
                for (int i = 0; i < 10; i++) {
                    try {
                        String element = dequeue();
                        System.out.println("Consumed: " + element);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
    
            producer.start();
            consumer.start();
        }
    }
    

以上三种方法都可以实现线程安全的队列。在实际应用中,建议使用java.util.concurrent包中的线程安全队列类,因为它们已经过优化,性能更好。

本文地址:https://www.ufcn.cn/tutorials/3385906.html

如非特殊说明,本站内容均来自于网友自主分享,概不代表本站观点,如有任何问题我们都将在收到反馈后的第一时间进行处理!