1、使用ThreadLocal
public class DateUtil {
private static final String DATE_FORMAT = “yyyy-MM-dd HH:mm:ss”;
private static final ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat(DATE_FORMAT);
}
};
public static DateFormat getDateFormat() {
return (DateFormat) threadLocal.get();
}
public static Date parse(String textDate) throws ParseException {
return getDateFormat().parse(textDate);
}
public static String format (Date textDate) throws ParseException {
return getDateFormat().format(textDate);
}
}
2、同步锁
public class DateUtil {
//使用同步
private static SimpleDateFormat sdf2 = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
public static String formatDate2(Date date){
synchronized(sdf2){
return sdf2.format(date);
}
}
public static Date parse2(String strDate) throws ParseException{
synchronized(sdf2){
return sdf2.parse(strDate);
}
}
}
3、需要的时候创建新实例
public class DateUtil {
public static Date getformatDateFromString(String date ) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
Date parse = format.parse(date);
return parse;
}
public static String getFromatDateFromDate(Date date){
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
return format.format(date);
}
}
4threadlocal另一种用法:
public class DateUtilByThreadLocal {
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){
return getDateFormat().format(date);
}
public static Date parse(String strDate) throws ParseException {
return getDateFormat().parse(strDate);
}
}