SimpleDateFormat线程不安全的5种解决方案
liuian 2025-07-01 21:19 41 浏览
1.什么是线程不安全?
线程不安全也叫非线程安全,是指多线程执行中,程序的执行结果和预期的结果不符的情况就叫着线程不安全。
线程不安全的代码
SimpleDateFormat 就是一个典型的线程不安全事例,接下来我们动手来实现一下。首先我们先创建 10 个线程来格式化时间,时间格式化每次传递的待格式化时间都是不同的,所以程序如果正确执行将会打印 10 个不同的值,接下来我们来看具体的代码实现:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SimpleDateFormatExample {
// 创建 SimpleDateFormat 对象
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
public static void main(String[] args) {
// 创建线程池
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// 执行 10 次时间格式化
for (int i = 0; i < 10; i++) {
int finalI = i;
// 线程池执行任务
threadPool.execute(new Runnable() {
@Override
public void run() {
// 创建时间对象
Date date = new Date(finalI * 1000);
// 执行时间格式化并打印结果
System.out.println(simpleDateFormat.format(date));
}
});
}
}
}我们预期的正确结果是这样的(10 次打印的值都不同):
然而,以上程序的运行结果却是这样的:
从上述结果可以看出,当在多线程中使用 SimpleDateFormat 进行时间格式化是线程不安全的。
2.解决方案
SimpleDateFormat 线程不安全的解决方案总共包含以下 5 种:
- 将 SimpleDateFormat 定义为局部变量;
- 使用 synchronized 加锁执行;
- 使用 Lock 加锁执行(和解决方案 2 类似);
- 使用 ThreadLocal;
- 使用 JDK 8 中提供的 DateTimeFormat。
接下来我们分别来看每种解决方案的具体实现。
① 将SimpleDateFormat变为局部变量
将 SimpleDateFormat 定义为局部变量时,因为每个线程都是独享 SimpleDateFormat 对象的,相当于将多线程程序变成“单线程”程序了,所以不会有线程不安全的问题,具体实现代码如下:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SimpleDateFormatExample {
public static void main(String[] args) {
// 创建线程池
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// 执行 10 次时间格式化
for (int i = 0; i < 10; i++) {
int finalI = i;
// 线程池执行任务
threadPool.execute(new Runnable() {
@Override
public void run() {
// 创建 SimpleDateFormat 对象
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
// 创建时间对象
Date date = new Date(finalI * 1000);
// 执行时间格式化并打印结果
System.out.println(simpleDateFormat.format(date));
}
});
}
// 任务执行完之后关闭线程池
threadPool.shutdown();
}
}以上程序的执行结果为:
当打印的结果都不相同时,表示程序的执行是正确的,从上述结果可以看出,将 SimpleDateFormat 定义为局部变量之后,就可以成功的解决线程不安全问题了。
② 使用synchronized加锁
锁是解决线程不安全问题最常用的手段,接下来我们先用 synchronized 来加锁进行时间格式化,实现代码如下:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SimpleDateFormatExample2 {
// 创建 SimpleDateFormat 对象
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
public static void main(String[] args) {
// 创建线程池
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// 执行 10 次时间格式化
for (int i = 0; i < 10; i++) {
int finalI = i;
// 线程池执行任务
threadPool.execute(new Runnable() {
@Override
public void run() {
// 创建时间对象
Date date = new Date(finalI * 1000);
// 定义格式化的结果
String result = null;
synchronized (simpleDateFormat) {
// 时间格式化
result = simpleDateFormat.format(date);
}
// 打印结果
System.out.println(result);
}
});
}
// 任务执行完之后关闭线程池
threadPool.shutdown();
}
}以上程序的执行结果为:
③ 使用Lock加锁
在 Java 语言中,锁的常用实现方式有两种,除了 synchronized 之外,还可以使用手动锁 Lock,接下来我们使用 Lock 来对线程不安全的代码进行改造,实现代码如下:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Lock 解决线程不安全问题
*/
public class SimpleDateFormatExample3 {
// 创建 SimpleDateFormat 对象
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
public static void main(String[] args) {
// 创建线程池
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// 创建 Lock 锁
Lock lock = new ReentrantLock();
// 执行 10 次时间格式化
for (int i = 0; i < 10; i++) {
int finalI = i;
// 线程池执行任务
threadPool.execute(new Runnable() {
@Override
public void run() {
// 创建时间对象
Date date = new Date(finalI * 1000);
// 定义格式化的结果
String result = null;
// 加锁
lock.lock();
try {
// 时间格式化
result = simpleDateFormat.format(date);
} finally {
// 释放锁
lock.unlock();
}
// 打印结果
System.out.println(result);
}
});
}
// 任务执行完之后关闭线程池
threadPool.shutdown();
}
}以上程序的执行结果为:
从上述代码可以看出,手动锁的写法相比于 synchronized 要繁琐一些。
④ 使用ThreadLocal
加锁方案虽然可以正确的解决线程不安全的问题,但同时也引入了新的问题,加锁会让程序进入排队执行的流程,从而一定程度的降低了程序的执行效率,如下图所示:
那有没有一种方案既能解决线程不安全的问题,同时还可以避免排队执行呢?
答案是有的,可以考虑使用 ThreadLocal。ThreadLocal 翻译为中文是线程本地变量的意思,字如其人 ThreadLocal 就是用来创建线程的私有(本地)变量的,每个线程拥有自己的私有对象,这样就可以避免线程不安全的问题了,实现如下:
知道了实现方案之后,接下来我们使用具体的代码来演示一下 ThreadLocal 的使用,实现代码如下:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* ThreadLocal 解决线程不安全问题
*/
public class SimpleDateFormatExample4 {
// 创建 ThreadLocal 对象,并设置默认值(new SimpleDateFormat)
private static ThreadLocal<SimpleDateFormat> threadLocal =
ThreadLocal.withInitial(() -> new SimpleDateFormat("mm:ss"));
public static void main(String[] args) {
// 创建线程池
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// 执行 10 次时间格式化
for (int i = 0; i < 10; i++) {
int finalI = i;
// 线程池执行任务
threadPool.execute(new Runnable() {
@Override
public void run() {
// 创建时间对象
Date date = new Date(finalI * 1000);
// 格式化时间
String result = threadLocal.get().format(date);
// 打印结果
System.out.println(result);
}
});
}
// 任务执行完之后关闭线程池
threadPool.shutdown();
}
}以上程序的执行结果为:
ThreadLocal和局部变量的区别
首先来说 ThreadLocal 不等于局部变量,这里的“局部变量”指的是像 2.1 示例代码中的局部变量, ThreadLocal 和局部变量最大的区别在于:ThreadLocal 属于线程的私有变量,如果使用的是线程池,那么 ThreadLocal 中的变量是可以重复使用的,而代码级别的局部变量,每次执行时都会创建新的局部变量,二者区别如下图所示:
更多关于 ThreadLocal 的内容,可以访问磊哥前面的文章《ThreadLocal不好用?那是你没用对!》。
⑤ 使用DateTimeFormatter
以上 4 种解决方案都是因为 SimpleDateFormat 是线程不安全的,所以我们需要加锁或者使用 ThreadLocal 来处理,然而,JDK 8 之后我们就有了新的选择,如果使用的是 JDK 8+ 版本,就可以直接使用 JDK 8 中新增的、安全的时间格式化工具类 DateTimeFormatter 来格式化时间了,接下来我们来具体实现一下。
使用 DateTimeFormatter 必须要配合 JDK 8 中新增的时间对象 LocalDateTime 来使用,因此在操作之前,我们可以先将 Date 对象转换成 LocalDateTime,然后再通过 DateTimeFormatter 来格式化时间,具体实现代码如下:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* DateTimeFormatter 解决线程不安全问题
*/
public class SimpleDateFormatExample5 {
// 创建 DateTimeFormatter 对象
private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("mm:ss");
public static void main(String[] args) {
// 创建线程池
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// 执行 10 次时间格式化
for (int i = 0; i < 10; i++) {
int finalI = i;
// 线程池执行任务
threadPool.execute(new Runnable() {
@Override
public void run() {
// 创建时间对象
Date date = new Date(finalI * 1000);
// 将 Date 转换成 JDK 8 中的时间类型 LocalDateTime
LocalDateTime localDateTime =
LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
// 时间格式化
String result = dateTimeFormatter.format(localDateTime);
// 打印结果
System.out.println(result);
}
});
}
// 任务执行完之后关闭线程池
threadPool.shutdown();
}
}以上程序的执行结果为:
3.线程不安全原因分析
要了解 SimpleDateFormat 为什么是线程不安全的?我们需要查看并分析 SimpleDateFormat 的源码才行,那我们先从使用的方法 format 入手,源码如下:
private StringBuffer format(Date date, StringBuffer toAppendTo,
FieldDelegate delegate) {
// 注意此行代码
calendar.setTime(date);
boolean useDateFormatSymbols = useDateFormatSymbols();
for (int i = 0; i < compiledPattern.length; ) {
int tag = compiledPattern[i] >>> 8;
int count = compiledPattern[i++] & 0xff;
if (count == 255) {
count = compiledPattern[i++] << 16;
count |= compiledPattern[i++];
}
switch (tag) {
case TAG_QUOTE_ASCII_CHAR:
toAppendTo.append((char)count);
break;
case TAG_QUOTE_CHARS:
toAppendTo.append(compiledPattern, i, count);
i += count;
break;
default:
subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols);
break;
}
}
return toAppendTo;
}也许是好运使然,没想到刚开始分析第一个方法就找到了线程不安全的问题所在。
从上述源码可以看出,在执行 SimpleDateFormat.format 方法时,会使用 calendar.setTime 方法将输入的时间进行转换,那么我们想象一下这样的场景:
- 线程 1 执行了 calendar.setTime(date) 方法,将用户输入的时间转换成了后面格式化时所需要的时间;
- 线程 1 暂停执行,线程 2 得到 CPU 时间片开始执行;
- 线程 2 执行了 calendar.setTime(date) 方法,对时间进行了修改;
- 线程 2 暂停执行,线程 1 得出 CPU 时间片继续执行,因为线程 1 和线程 2 使用的是同一对象,而时间已经被线程 2 修改了,所以此时当线程 1 继续执行的时候就会出现线程安全的问题了。
正常的情况下,程序的执行是这样的:
非线程安全的执行流程是这样的:
在多线程执行的情况下,线程 1 的 date1 和线程 2 的 date2,因为执行顺序的问题,最终都被格式化成 date2 formatted,而非线程 1 date1 formatted 和线程 2 date2 formatted,这样就会导致线程不安全的问题。
4.各方案优缺点总结
如果使用的是 JDK 8+ 版本,可以直接使用线程安全的 DateTimeFormatter 来进行时间格式化,如果使用的 JDK 8 以下版本或者改造老的 SimpleDateFormat 代码,可以考虑使用 synchronized 或 ThreadLocal 来解决线程不安全的问题。因为实现方案 1 局部变量的解决方案,每次执行的时候都会创建新的对象,因此不推荐使用。synchronized 的实现比较简单,而使用 ThreadLocal 可以避免加锁排队执行的问题。
相关推荐
- 网络上xp是什么梗(xp是什么意思网络)
-
x是喜欢的意思,p是偏好的意思,原神xp党指的是一直在使用XP系统玩原神,不愿意更新系统的人。
- 电脑如何升级到win7
-
Windows7升级到Windows10系统需要使用官方的升级功能完成,以下是具体的操作方法:?1、在微软Windows10网站下载系统版本工具,完成右键以管理员身份打开【MediaCreationT...
- 手机下载pe启动盘(手机pe启动盘制作工具)
-
使用手机制作电脑PE启动盘需要以下步骤:1.手机需要支持OTG功能,并插入U盘。2.下载并安装一个名为“Rufus”的应用程序,它可以将U盘制作成可引导的PE启动盘。3.打开Rufus应用程序,...
- 2025年路由器推荐(2021年值得买的路由器)
-
水星AX18G这个无线速率是1800Mbps也属于“阉割”版的,跟标准的WiFi6还有一定差距。不过价格便宜,也可以作为WiFi6的尝试产品家里有宽带的话,买个无线路由器,约100元左右就行。每月交宽...
- 磁盘分区形式(磁盘分区形式MBR与GPT怎么转换)
-
怎么进行磁盘分区,可以参考以下步骤:步骤1.在“此电脑”上右键点击,选择“管理”,然后在“计算机管理”窗口的左侧列表中选择“磁盘管理”。在Windows10中也可以右键点击开始菜单,直接选择“磁盘...
- 固态硬盘使用寿命(固态硬盘使用寿命多久)
-
2012年9月买的联想U410超极本,到目前五年多,使用6300小时左右,电池损耗率只有15%+,固态硬盘升级120GB+原装的500GB机械硬盘,内存升级到16GB(上限了),加上Primocach...
- general(general是什么意思)
-
GENERAL的意思是:1、adj.一般的,普通的;综合的;大体的2、n.一般;将军,上将;常规短语:1、generaldesign总体设计2、generalhospital总医院;综合医...
- 手机处理器排名最新图(手机处理器排行榜全部)
-
众所周知,手机端SOC很少在插电模式下运行,因此能耗比在移动端CPU性能中特别重要。本文整理了主流的SOC能耗比情况,给大家购买手机做一个参考。SOC能耗比较高的,包括麒麟810,骁龙625,麒麟65...
- pdf版本怎么弄(怎么把word转为pdf)
-
回答如下:要将PDF文件恢复到以前的版本,您需要执行以下步骤:1.找到保存PDF文件的文件夹或位置。2.在该位置中找到以前的版本,这可能是备份文件、自动保存文件或之前保存的版本。3.如果您没有备...
- 万能bt搜索引擎网站(bt万能搜索破解版)
-
最好用最全面的的磁力搜索引擎是磁力熊,因为它是一个内容丰富、还是功能最为强大的一个磁力搜索网站,通过它不仅仅可以搜索磁力熊磁力熊,是一个内容丰富、功能最为强大的一个磁力搜索网站,通过它不仅仅可以搜索...
- 苹果id注册官网登录(appleid官网注册账号)
-
浏览器访问申请AppleID官网注册 1、在浏览器地址栏上面输入:“https://appleid.apple.com/cn”,进入申请AppleID官网界面,点击下面的“创建AppleID...
- 苹果笔记本怎么下载windows系统
-
方法一:使用BootCamp方法二:使用虚拟机方法三:使用Wine简介BootCamp是苹果电脑自带的一个软件,可以帮助用户在Mac上安装Windows操作系统。虚拟机则是运行在Mac上的一个软件...
- 华硕电脑激活码(华硕电脑windows激活码在哪里)
-
你所说的应该是系统激活密钥吧华硕OEM密钥就行!HomePremium(家庭高级版):27GBM-Y4QQC-JKHXW-D9W83-FJQKDUltimate(旗舰版):6K2KY-BF...
- 一周热门
-
-
飞牛OS入门安装遇到问题,如何解决?
-
如何在 iPhone 和 Android 上恢复已删除的抖音消息
-
Boost高性能并发无锁队列指南:boost::lockfree::queue
-
大模型手册: 保姆级用CherryStudio知识库
-
用什么工具在Win中查看8G大的log文件?
-
如何在 Windows 10 或 11 上通过命令行安装 Node.js 和 NPM
-
威联通NAS安装阿里云盘WebDAV服务并添加到Infuse
-
Trae IDE 如何与 GitHub 无缝对接?
-
idea插件之maven search(工欲善其事,必先利其器)
-
如何修改图片拍摄日期?快速修改图片拍摄日期的6种方法
-
- 最近发表
- 标签列表
-
- python判断字典是否为空 (50)
- crontab每周一执行 (48)
- aes和des区别 (43)
- bash脚本和shell脚本的区别 (35)
- canvas库 (33)
- dataframe筛选满足条件的行 (35)
- gitlab日志 (33)
- lua xpcall (36)
- blob转json (33)
- python判断是否在列表中 (34)
- python html转pdf (36)
- 安装指定版本npm (37)
- idea搜索jar包内容 (33)
- css鼠标悬停出现隐藏的文字 (34)
- linux nacos启动命令 (33)
- gitlab 日志 (36)
- adb pull (37)
- python判断元素在不在列表里 (34)
- python 字典删除元素 (34)
- vscode切换git分支 (35)
- python bytes转16进制 (35)
- grep前后几行 (34)
- hashmap转list (35)
- c++ 字符串查找 (35)
- mysql刷新权限 (34)
