SimpleDateFormat线程不安全-使用ThreadLocal解决

说明

使用 ThreadLocal 对象来保存 SimpleDateFormat 对象

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

public class SimpleDataFormatThread解决 {

    public static class MyThread implements Runnable{
        // 声明 ThreadLocal 成员变量
        ThreadLocal<SimpleDateFormat> tl = new ThreadLocal(){
            // 每次线程调用get() 方法时,都执行该方法
            @Override
            protected Object initialValue() {
                // 必须在该方法中创建对象,否则还是报错
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return sdf;
            }
        };
        @Override
        public void run() {
            try {
                Date date = tl.get().parse("2023-08-25 09:00:00");
                System.out.println(date);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
    }


    public static void main(String[] args) {
        MyThread mt = new MyThread();
        for (int i=0;i<10;i++) {
            Thread t = new Thread(mt);
            t.start();
        }
    }
}