Java8新特性——————SimpleDateFormat格式化的線程安全問題

傳統時間格式化的線程安全問題

在使用SimpleDateFormat時間格式處理類會出現線程安全問題,而java8新特性中的 DateTimeFormatter時間格式處理類解決了此問題,代碼如下:

    @Test
    public static void main(String[] args)throws Exception {
        //出現線程安全問題:異常信息爲java.lang.NumberFormatException: For input string: ".22E1.22E1"
/*        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Callable<Date> callable = new Callable<Date>() {
            @Override
            public Date call() throws Exception {
                return sdf.parse("20200220");
            }
        };*/
        //加鎖後操作
/*        Callable<Date> callable = new Callable<Date>() {
            @Override
            public Date call() throws Exception {
                return DateFormatThreadLocal.convert("20200220");
            }
        };*/
        //java8時間處理類
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
        Callable<LocalDate> callable = new Callable<LocalDate>() {
            @Override
            public LocalDate call() throws Exception {
                return LocalDate.parse("20200220",dtf);
            }
        };
        ExecutorService pool = Executors.newFixedThreadPool(10);
        List<Future<LocalDate>> futures = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            futures.add(pool.submit(callable));
        }
        for (Future<LocalDate> future : futures) {
            System.out.println(future.get());
        }
        pool.shutdown();
    }
//加鎖
class  DateFormatThreadLocal{
    private  static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>(){
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyyMMdd");
        }
    };

    public static  Date convert(String source) throws ParseException {
        return df.get().parse(source);
    }

計算兩個"時間"之間的間隔

@Test
public static void main(String[] args)throws Exception {
    Instant ins1 = Instant.now();
    Thread.sleep(10000);
    Instant ins2 = Instant.now();
    Duration durantion = Duration.between(ins1, ins2);
    System.out.println(durantion.toMillis());//10000毫秒
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章