您的位置:首页 > 其它

SimpleDateFormat和DateFormat类不是线程安全的。

2015-11-23 00:00 525 查看
摘要: JDK原始文档如下:
  Synchronization:
  Date formats are not synchronized.
  It is recommended to create separate format instances for each thread.
  If multiple threads access a format concurrently, it must be synchronized externally.

比较好的两种方法

import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class ConcurrentDateUtil {    private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
@Override        protected DateFormat initialValue() {            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};    public static Date parse(String dateStr) throws ParseException {        return threadLocal.get().parse(dateStr);
}    public static String format(Date date) {        return threadLocal.get().format(date);
}
}

import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class ThreadLocalDateUtil {    private static final String date_format = "yyyy-MM-dd HH:mm:ss";    private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>();

public static DateFormat getDateFormat()
{
DateFormat df = threadLocal.get();
if(df==null){
df = new SimpleDateFormat(date_format);
threadLocal.set(df);
}
return df;
}

public static String formatDate(Date date) throws ParseException {        return getDateFormat().format(date);
}    public static Date parse(String strDate) throws ParseException {        return getDateFormat().parse(strDate);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: