スレッド安全性の問題がフォーマットのSimpleDateFormat ------ Java8の新機能

スレッド安全性の問題の伝統的な時間フォーマット

DateTimeFormatter時間形式でjava8新機能がクラスを処理している間の時間では、SimpleDateFormatのクラススレッドの安全性の問題を使用してそこに書式設定されます、次のように、この問題を解決します。

    @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);
    }

2「時間」の間の間隔を計算します

@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毫秒
}
公開された67元の記事 ウォン称賛19 ビュー9863

おすすめ

転載: blog.csdn.net/qq_41530004/article/details/104585331