一、ThreadLocal的使用场景
(1)使用日期工具类,当用到SimpleDateFormat时,使用ThreadLocal保证线程安全;
(2)全局存储用户信息(用户信息存入ThreadLocal,那么当前线程在任何地方需要时,都可以使用);
(3)保证同一个线程,获取的数据库连接Connection是同一个,使用ThreadLocal来解决线程安全问题;
二、 SimpleDateFormat线程不安全
2.1、SimpleDateFormatUtil
/**
* @Author : 一叶浮萍归大海
* @Date: 2023/11/22 15:25
* @Description:
*/
public class SimpleDateFormatUtil {
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static Date parseDate(String dateString) {
Date date = null;
try {
date = sdf.parse(dateString);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
}
2.2、SimpleDateFormatMainApp
/**
* @Author : 一叶浮萍归大海
* @Date: 2023/11/22 15:27
* @Description:
*/
public class SimpleDateFormatMainApp {
/**
* 线程池
*/
static final ExecutorService pool = new ThreadPoolExecutor(
2,
10,
2L,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(20),
Executors.defaultThreadFactory(),
// new ThreadPoolExecutor.AbortPolicy
// new ThreadPoolExecutor.CallerRunsPolicy
// new ThreadPoolExecutor.DiscardOldestPolicy
new ThreadPoolExecutor.DiscardOldestPolicy());
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
pool.execute(() -> {
System.out.println(String.format(String.format(Thread.currentThread().getName() + "===>" + SimpleDateFormatUtil.parseDate("2023-11-11 18:00:00"))));
});
}
}
}
三、 SimpleDateFormat线程不安全(解决)
3.1、SimpleDateFormatUtil
/**
* @Author : 一叶浮萍归大海
* @Date: 2023/11/22 15:25
* @Description:
*/
public class SimpleDateFormatUtil {
private static final ThreadLocal<SimpleDateFormat> threadLocal = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
public static Date parseDate(String dateString) {
Date date = null;
try {
date = threadLocal.get().parse(dateString);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
}
3.2、SimpleDateFormatMainApp
同上。