package com.maxbox.test;


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;

/**
 * SimpleDateFormat线程不安全
 * DateTimeFormatter 线程安全的
 * Created by guohui on 2019/4/10.
 */
public class SimpleDateFormatTest {
//    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final String pattern = "yyyy-MM-dd HH:mm:ss";

    private static final SimpleDateFormat formatter2 =  new SimpleDateFormat(pattern);

    private static final DateTimeFormatter formatter1  = DateTimeFormatter.ofPattern(pattern);

    public static String formatDate(LocalDateTime date){
        return formatter1.format(date);
    }
    public static LocalDateTime parse(String dateNow){
        return LocalDateTime.parse(dateNow,formatter1);
    }

    public static String formatDate2(Date date) throws ParseException{
        return formatter2.format(date);
    }

    public static Date parse2(String dateNow) throws ParseException {
        return formatter2.parse(dateNow);
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(100);

        /*for (int i =0 ;i<1;i++){
            executorService.execute(()->{
//                for (int j = 0; j < 10; j++) {
                    try {
                        System.out.println(parse2(formatDate2(new Date())));
//                        System.out.println(parse(formatDate(LocalDateTime.now())));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
//                }
            });
        }*/

        for (int i = 0; i < 10; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(4000);
                        System.out.println(parse(formatDate(LocalDateTime.now())));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        executorService.shutdown();
//        executorService.awaitTermination(1, TimeUnit.DAYS);

        while(!executorService.awaitTermination(3, TimeUnit.SECONDS)){
            System.out.println("service not stop");
        }
        System.out.println("all thread complete");
    }
}
