DateTimeFormatter是线程安全的

DateTimeFormatter和SimpleDateFormat_实例化

SimpleDateFormat线程不安全

SimpleDateFormat推荐每个线程实例化该对象,如果多个线程访问1个SimpleDateFormat,必须在外部使用同步

DateTimeFormatter和SimpleDateFormat_实例化_02

 

 

threadlocal方式


static ThreadLocal<SimpleDateFormat> simpleDateFormatThreadLocal = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    public static String now() {
        return simpleDateFormatThreadLocal.get().format(new Date());
    }

同步方式


  private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static String dateToString(Date date)throws ParseException {
        synchronized(sdf){
            return sdf.format(date);
        }
    }

    public static Date stringToDate(String stringDate) throws ParseException{
        synchronized(sdf){
            return sdf.parse(stringDate);
        }
    }

DateTimeFormatter


 // 綫程安全
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

// 現在時間转字符串
LocalDateTime now = LocalDateTime.now();
String nowTime = now.format(formatter);
System.out.println("nowTime=" + nowTime);