private static final String date_format = "yyyy-MM-dd HH:mm:ss";
//使用ThreadLocal为每个线程都创建一个线程独享的SimpleDateFormat变量
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>();
//获取DateFormat 当DateFormat获取不到的时候会初始化一个返回并放到ThreadLocal 中
public static DateFormat getDateFormat() {
DateFormat df = threadLocal.get();
if(df==null){
df = new SimpleDateFormat(date_format);
threadLocal.set(df);
}
return df;
}
public static String getNowDate(){
Date date = new Date();
return getDateFormat().format(date);
}
SimpleDateFormat线程不安全解决方案
最新推荐文章于 2025-03-19 19:42:28 发布