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

360影视 国产动漫 2025-05-12 06:40 1

摘要:public class HashMapConcurrentIssue { static Map map = new HashMap; public static void main(String args) { Exec

java

public class UnsafeListDemo { public static void main(String args) throws InterruptedException { List list = new ArrayList; Thread t1 = new Thread( -> { for (int i = 0; i { for (int i = 0; i

java

List safeList = new CopyOnWriteArrayList;// 线程操作代码同上// 最终输出保证为2000

java

List syncList = Collections.synchronizedList(new ArrayList);// 线程操作代码同上

java

public class HashMapConcurrentIssue { static Map map = new HashMap; public static void main(String args) { ExecutorService executor = Executors.newFixedThreadPool(10); for (int i = 0; i { for (int j = 0; j

java

Map concurrentMap = new ConcurrentHashMap;// 线程操作代码同上

java

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

java

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

java

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

java

public class ProducerConsumerDemo { private static final BlockingQueue 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; }}

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 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 collection) { long start = System.currentTimeMillis; ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT); for (int i = 0; i { for (int j = 0; j ); // 线程不安全,结果可能异常 test(new Vector); // 同步锁性能较低 test(new CopyOnWriteArrayList); // 写时复制适合读多写少 }}# 查看线程状态jstack

# 监控内存使用jstat -gcutil

1000# 性能分析jvisualvm

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

来源:大龄程序猿小武

相关推荐