ThreadLocal对SimpleDataFormat的使用

来源:互联网 发布:2017淘宝总消费怎么查 编辑:程序博客网 时间:2024/06/15 10:47
package threadLocal;import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;/** * ThreadLocal使用方法1 *  * @author mxp *  */public class MyThreadLocal {    private static ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<SimpleDateFormat>() {        @Override        protected SimpleDateFormat 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);    }}/** * ThreadLocal使用方法2 *  * @author mxp *  */class MythreadLocal2 {    private static ThreadLocal<DateFormat> local = new ThreadLocal<DateFormat>();    private static DateFormat initValue() {        DateFormat dateFormat = local.get();        if (dateFormat == null) {            dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");            local.set(dateFormat);        }        return dateFormat;    }    public static Date parse(String dateStr) throws ParseException {        return initValue().parse(dateStr);    }    public static String format(Date date) {        return initValue().format(date);    }}

0 0