Java集合与并发编程深度解析:常用类、线程安全实现与底层原理

Java集合与并发编程深度解析:常用类、线程安全实现与底层原理

编程文章jaq1232025-05-22 11:03:474A+A-

一、ArrayList线程安全问题与解决方案

问题演示

java

public class UnsafeListDemo {
    public static void main(String[] args) throws InterruptedException {
        List<Integer> list = new ArrayList<>();
        
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(i);
            }
        });
        
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(i);
            }
        });
        
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("最终大小: " + list.size()); // 结果可能小于2000
    }
}

解决方案1:使用CopyOnWriteArrayList

java

List<Integer> safeList = new CopyOnWriteArrayList<>();

// 线程操作代码同上
// 最终输出保证为2000

解决方案2:使用同步包装类

java


List<Integer> syncList = Collections.synchronizedList(new ArrayList<>());

// 线程操作代码同上

二、HashMap并发问题与ConcurrentHashMap

问题演示(可能引发死循环)

java


public class HashMapConcurrentIssue {
    static Map<String, Integer> map = new HashMap<>();

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            final int key = i;
            executor.execute(() -> {
                for (int j = 0; j < 1000; j++) {
                    map.put(String.valueOf(key), j);
                }
            });
        }
        executor.shutdown();
        // 可能产生数据丢失或死循环
    }
}

解决方案:ConcurrentHashMap

java


Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();

// 线程操作代码同上

三、原子操作计数器对比

问题演示(synchronized方案)

java


class SynchronizedCounter {
    private int count = 0;
    
    public synchronized void increment() {
        count++;
    }
    
    public synchronized int get() {
        return count;
    }
}

优化方案:AtomicLong

java


class AtomicCounter {
    private AtomicLong count = new AtomicLong(0);
    
    public void increment() {
        count.incrementAndGet();
    }
    
    public long get() {
        return count.get();
    }
}

高性能方案:LongAdder(适合高并发统计)

java


class LongAdderCounter {
    private LongAdder adder = new LongAdder();
    
    public void increment() {
        adder.increment();
    }
    
    public long get() {
        return adder.sum();
    }
}

四、生产者-消费者模式实现

使用BlockingQueue实现

java


public class ProducerConsumerDemo {
    private static final BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10);

    public static void main(String[] args) {
        // 生产者
        new Thread(() -> {
            try {
                for (int i = 0; ; i++) {
                    queue.put(i);
                    System.out.println("生产: " + i);
                    Thread.sleep(200);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        // 消费者
        new Thread(() -> {
            try {
                while (true) {
                    Integer item = queue.take();
                    System.out.println("消费: " + item);
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

五、锁机制对比示例

ReentrantLock基本使用

java


class LockDemo {
    private final ReentrantLock lock = new ReentrantLock();
    private int count = 0;

    public void safeIncrement() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }
}

读写锁应用

java


class ReadWriteCache {
    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private final Map<String, Object> cache = new HashMap<>();

    public Object get(String key) {
        rwLock.readLock().lock();
        try {
            return cache.get(key);
        } finally {
            rwLock.readLock().unlock();
        }
    }

    public void put(String key, Object value) {
        rwLock.writeLock().lock();
        try {
            cache.put(key, value);
        } finally {
            rwLock.writeLock().unlock();
        }
    }
}

六、并发集合性能测试对比

java


public class CollectionPerformanceTest {
    static final int THREAD_COUNT = 100;
    static final int OPERATION_COUNT = 100000;

    static void test(Collection<Integer> collection) {
        long start = System.currentTimeMillis();
        ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);
        
        for (int i = 0; i < THREAD_COUNT; i++) {
            executor.execute(() -> {
                for (int j = 0; j < OPERATION_COUNT; j++) {
                    collection.add(j);
                }
            });
        }
        
        executor.shutdown();
        while (!executor.isTerminated());
        long duration = System.currentTimeMillis() - start;
        System.out.println(collection.getClass().getSimpleName() + " 耗时: " + duration + "ms");
    }

    public static void main(String[] args) {
        test(new ArrayList<>());            // 线程不安全,结果可能异常
        test(new Vector<>());               // 同步锁性能较低
        test(new CopyOnWriteArrayList<>());  // 写时复制适合读多写少
    }
}

最佳实践总结

  1. 根据场景选择工具
  2. 读多写少 → CopyOnWriteArrayList
  3. 写多读少 → ConcurrentHashMap
  4. 精确控制 → ReentrantLock
  5. 简单原子操作 → Atomic类
  6. 性能优化技巧
  7. 避免在锁内执行耗时操作
  8. 使用ConcurrentHashMap的分段锁机制
  9. 优先考虑无锁编程(CAS)
  10. 问题排查工具
# 查看线程状态
jstack <pid> 

# 监控内存使用
jstat -gcutil <pid> 1000

# 性能分析
jvisualvm

这些案例覆盖了Java并发编程中最常见的场景,开发者应根据具体需求选择最合适的并发工具和集合类,同时结合性能测试工具进行验证。

点击这里复制本文地址 以上内容由jaq123整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!

苍茫编程网 © All Rights Reserved.  蜀ICP备2024111239号-21