多線程時候使用

ThreadLocal可以確保每個線程都可以得到單獨的一個SimpleDateFormat的對象,那麼自然也就不存在競爭問題了。 

   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 Exception {

        return threadLocal.get().parse(dateStr);
    }


    public static String format(Date date) {

        return threadLocal.get().format(date);
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章