欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用ThreadLocal解决SimpleDateFormat线程不安全问题

程序员文章站 2022-05-14 09:29:43
...
import java.text.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DataUtils {

    private DataUtils() {

    }

    /**
     * key为pattern value为存有ThreadLocal
     */
    private static Map<String, ThreadLocal<SimpleDateFormat>> sdfMap = new HashMap<>();

    /**
     * 初始化sdfMap
     *
     * @param pattern
     * @return
     */
    private static ThreadLocal<SimpleDateFormat> initSdfMap(String pattern) {
        //如果sdfMap有pattern的value就直接返回,如果没有就创建一个,然后返回
        ThreadLocal<SimpleDateFormat> t1 = sdfMap.computeIfAbsent(pattern, p ->
                //用ThreadLocal作为容器,当每个线程访问这个 threadLocal 变量时,ThreadLocal会为每个线程提供一份变量,各个线程互不影响。
                ThreadLocal.withInitial(() -> new SimpleDateFormat(pattern))
        );

        return t1;
    }

    public static String getDataStr(Date date, String pattern) {
        SimpleDateFormat simpleDateFormat = initSdfMap(pattern).get();
        return simpleDateFormat.format(date);
    }

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


        executorService.execute(() -> System.out.println(getDataStr(new Date("2021/01/17"), "yyyy-MM-dd")));
        executorService.execute(() -> System.out.println(getDataStr(new Date("2021/02/17"), "yyyy-MM-dd")));
        executorService.execute(() -> System.out.println(getDataStr(new Date("2021/03/17"), "yyyy-MM-dd")));
        executorService.execute(() -> System.out.println(getDataStr(new Date("2021/04/17"), "yyyy-MM-dd")));
        executorService.execute(() -> System.out.println(getDataStr(new Date("2021/05/17"), "yyyy-MM-dd")));
        executorService.execute(() -> System.out.println(getDataStr(new Date("2021/06/17"), "yyyy-MM-dd")));
        executorService.execute(() -> System.out.println(getDataStr(new Date("2021/07/17"), "yyyy-MM-dd")));
        executorService.execute(() -> System.out.println(getDataStr(new Date("2021/08/17"), "yyyy-MM-dd")));
        executorService.execute(() -> System.out.println(getDataStr(new Date("2021/09/17"), "yyyy-MM-dd")));
        executorService.execute(() -> System.out.println(getDataStr(new Date("2021/10/17"), "yyyy-MM-dd")));
        executorService.execute(() -> System.out.println(getDataStr(new Date("2021/11/17"), "yyyy-MM-dd")));
        executorService.execute(() -> System.out.println(getDataStr(new Date("2021/12/17"), "yyyy-MM-dd")));
        executorService.shutdown();
    }


}

线程不安全的本质,多个线程操作共享变量

相关标签: base