java 单元测试中验证并发安全的核心做法是使用 executorservice 配合多个线程同时执行目标方法,并通过 countdownlatch 确保所有线程同步启动和结束。具体实现时,需定义共享状态或资源,在测试方法中创建固定数量的线程,提交任务后等待完成,最后断言结果符合预期。若存在竞态条件,程序通常会抛出异常或产生错误数据,从而暴露并发缺陷。

如何模拟多线程竞争环境
使用 Executors.newFixedThreadPool 创建线程池,并利用 CountDownLatch 控制线程启动时机,确保所有线程在同一时刻访问共享资源。这种设置能最大化触发竞态条件的概率,是验证并发安全的基础步骤。

import java.util.concurrent.*;
public class ConcurrentTest {
public static void main(String[] args) throws Exception {
int threadCount = 10;
CountDownLatch startLatch = new CountDownLatch(1);
CountDownLatch endLatch = new CountDownLatch(threadCount);
// 假设有一个非线程安全的计数器
Counter counter = new Counter();
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
for (int i = 0; i < threadCount; i++) {
executor.submit(() -> {
try {
startLatch.await(); // 等待开始信号
counter.increment(); // 执行操作
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
endLatch.countDown(); // 通知结束
}
});
}
startLatch.countDown(); // 释放所有线程
endLatch.await(); // 等待所有线程完成
executor.shutdown();
System.out.println("Final count: " + counter.getCount());
}
}
class Counter {
private int count = 0;
public void increment() { count++; }
public int getCount() { return count; }
}
运行上述代码,由于 Counter 未加锁,最终输出通常小于 10,证明存在并发问题。若改为线程安全实现,输出应为 10。
立即学习“Java免费学习笔记(深入)”;
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
如何验证原子性操作的正确性
对于需要保证原子性的操作,应使用 AtomicInteger 或 synchronized 块包裹关键代码。在测试中,通过多次重复并发调用并断言最终值等于预期值(如线程数),可验证原子性是否生效。若使用 ReentrantLock,需确保在 finally 块中释放锁,避免死锁。

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class AtomicTest {
public static void main(String[] args) throws Exception {
int threadCount = 100;
CountDownLatch startLatch = new CountDownLatch(1);
CountDownLatch endLatch = new CountDownLatch(threadCount);
AtomicInteger atomicCounter = new AtomicInteger(0);
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
for (int i = 0; i < threadCount; i++) {
executor.submit(() -> {
try {
startLatch.await();
atomicCounter.incrementAndGet(); // 原子操作
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
endLatch.countDown();
}
});
}
startLatch.countDown();
endLatch.await();
executor.shutdown();
System.out.println("Atomic count: " + atomicCounter.get());
}
}
此示例中,AtomicInteger 保证每次递增都是原子的,最终输出恒为 100,验证了原子性操作的有效性。
当共享资源被意外修改时会发生什么
若共享资源未被正确保护,例如在 Counter 类中直接修改 count 字段而未加同步,多线程环境下会出现数据丢失。此时,断言会失败,因为最终值不等于预期值。开发者应检查代码中是否有非原子复合操作,如先读取再写入,这类操作在并发下极易出错。修复方法是引入 synchronized 或 java.util.concurrent 包中的工具类。

















