在工具类中有2个时间格式化和字符串转换成时间的函数,使用了类静态变量
SimpleDateFormat,具体代码如下:
在多线程下使用时,报如下错误:
可以采用synchronized锁将代码改成如下:
SimpleDateFormat,具体代码如下:
或者采用如下方式:
public class Utils
{
/**
* 注意 SimpleDateFormat 不是线程同步的,必须用 ThreadLocal
*/
private static ThreadLocal<DateFormat> THREAD_LOCAL = new ThreadLocal<DateFormat>() {
protected synchronized DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
}
};
public static DateFormat getDateFormat() {
return THREAD_LOCAL.get();
}
public static String getLocalTime(Date d)
{
Date tmp = d;
if (tmp == null)
tmp = new Date();
String ret = getDateFormat().format(tmp);
return ret;
}
public static Date parse2Time(String date)
{
try
{
if (date.length() == 8)
date = date + "000000";
Date d = getDateFormat().parse(date);
}
catch (ParseException e)
{
LogUtils.Log(logger, e);
}
return d;
}
}
测试以上方法较commons-lang包中的DateUtils.parse(String time)性能要高,而且在DateUtils.parse()中也是调用SimpleDateFormat的方法的。