package com.sqbj.smart.bacs.utils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* @Description 保证格式化日期线程安全
* @Author fengzt
* @Date 2019/2/18
* @Version 1.0
**/
public class TimeTest{
private static final SimpleDateFormatSIMPLE_DATE_FORMAT =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final ThreadLocal<DateFormat> DATE_FORMAT_THREAD_LOCAL =new ThreadLocal<DateFormat>(){
@Override
protected DateFormatinitialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
private static final DateTimeFormatterDATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/**
* @Description 线程不安全
* @author fengzt
*/
private static StringformatDate(Date date) {
return SIMPLE_DATE_FORMAT.format(date);
}
private static Dateparse(String strDate) throws ParseException{
return SIMPLE_DATE_FORMAT.parse(strDate);
}
/**
* @Description 线程安全
* @author fengzt
*/
private static StringformatDate0(Date date) {
return DATE_FORMAT_THREAD_LOCAL.get().format(date);
}
private static Dateparse0(String strDate) throws ParseException{
return DATE_FORMAT_THREAD_LOCAL.get().parse(strDate);
}
private synchronized static StringformatDate1(Date date) {
return SIMPLE_DATE_FORMAT.format(date);
}
private synchronized static Dateparse1(String strDate) throws ParseException{
return SIMPLE_DATE_FORMAT.parse(strDate);
}
private static StringformatDate2(LocalDateTime localDateTime) {
return DATE_TIME_FORMATTER.format(localDateTime);
}
private static LocalDateTimeparse2(String strDate) {
return LocalDateTime.parse(strDate,DATE_TIME_FORMATTER);
}
public static void main(String[] args) {
//单线程
System.out.printf(formatDate(new Date()));
//多线程
ExecutorService executor = Executors.newFixedThreadPool(100);
for (int i =0; i <20 ; i++) {
executor.execute(() ->{
for (int j =0; j <10 ; j++) {
try {
System.out.println(parse0("2019-02-18 18:00:00"));
System.out.println(parse1("2019-02-18 18:00:00"));
System.out.println(parse2(formatDate2(LocalDateTime.now())));
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
executor.shutdown();
try {
executor.awaitTermination(1,TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}