并发条件下SimpleDateFormat线程不安全及解决方案

1、使用线程池创建并发环境解析日期

package com.zh.time;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @desc SimpleDateFormat 线程不安全
 * @author zhanh247
 */
public class SimpleDateFormatTest {

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        try {
            Callable<Date> callable = new Callable<Date>() {
                @Override
                public Date call() throws Exception {
                    return sdf.parse("20180909");
                }
            };
            List<Future<Date>> list = new ArrayList<Future<Date>>();

            for (int i = 0; i < 10; i++) {
                list.add(executorService.submit(callable));
            }

            for (Future<Date> future : list) {
                System.out.println(future.get());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }

}

2、执行结果如下:

并发条件下SimpleDateFormat线程不安全及解决方案

 

 3、线程不安全问题解决方案

package com.zh.time;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @desc 线程安全
 * @author zhanh247
 */
public class SimpleDateFormatThreadLocal {

    private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyyMMdd");
        };
    };

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

 

上一篇:Future 异步任务 in Java


下一篇:Concurrent包下用过哪些类?