前言
SimpleDateFormat 是 Java 中一个常用的类,该类用来对日期字符串进行解析和格式化输出,但如果使用不小心会导致线程安全问题,在多线程环境下使用使用同步代码来避免问题。
1、问题复现
为了重现 SimpleDateFormat 类的线程安全问题,一种比较简单的方式就是使用线程池结合 Java 并发包中的 CountDownLatch 类和 Semaphore 类来重现线程安全问题。
public class SimpleDateFormatTest01 {
//执行总次数
private static final int EXECUTE_COUNT = 1000;
//同时运行的线程数量
private static final int THREAD_COUNT = 20;
//SimpleDateFormat对象
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static void main(String[] args) throws InterruptedException {
final Semaphore semaphore = new Semaphore(THREAD_COUNT);
final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < EXECUTE_COUNT; i++) {
executorService.execute(() -> {
try {
semaphore.acquire();
try {
simpleDateFormat.parse("2020-01-01");
} catch (ParseException e) {
System

文章讨论了Java中SimpleDateFormat类在线程环境下的线程安全问题,通过一个示例展示了如何复现这个问题,导致NumberFormatException。分析原因在于Calendar对象的线程不安全。文章提出了两种解决方案:使用ThreadLocal存储每个线程的SimpleDateFormat副本,以及利用Java8的DateTimeFormatter类,后者是线程安全的,适合高并发场景。
最低0.47元/天 解锁文章
4401

被折叠的 条评论
为什么被折叠?



