避坑!SimpleDateFormat不光线程不安全,还有这个隐患

数据库80

众所周知,SimpleDateFormat是多线程不安全的

下面这段代码通过多线程使用同一个SimpleDateFormat对象的parse方法, 多次执行代码来测试,可以看到会出现两种预想不到的现象----->要么出现不正确的时间解析结果,要么抛出message各异的NumberFormatException异常。 @see>>借助SimpleDateFormat来谈谈java里的多线程不安全

package jstudy.dateformat;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpleDateFormatTest {
public static void main(String[] args) throws ParseException, InterruptedException {
ExecutorService threadPool = Executors.newFixedThreadPool(20);
SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String startDate = "2022-01-07 15:40:15";
for (int i = 0; i < 20; i++) {
threadPool.execute(() -> {
for (int j = 0; j < 20; j++) {
try {
// new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startDate); //使用局部变量可以避免出现线程不安全

输入验证码查看隐藏内容

扫描二维码关注本站微信公众号 Johngo学长
或者在微信里搜索 Johngo学长
回复 svip 获取验证码
wechat Johngo学长