[技术分享]20180109_多线程_ ThreadLocal解决线程安全问题(jdk 1.7)
下面存在一个线程安全问题:
public class TestSimpleDateFormat { public static void main(String[] args) throws InterruptedException, ExecutionException { //SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd"); //java 8可用 Callable<LocalDate> task = new Callable<LocalDate>() { @Override public LocalDate call() throws Exception { return LocalDate.parse("20180109", dtf); //java 8可用 //return DateFormatThreadLocal.convert("20180109"); } }; List<Future<LocalDate>> list = new ArrayList<>(); ExecutorService pool = Executors.newFixedThreadPool(10); for(int i=0;i<10;i++){ list.add(pool.submit(task)); } for(Future<LocalDate> future:list){ System.out.println(future.get()); } pool.shutdown();//记得关闭 } }
下面是threadLocal类:
public class DateFormatThreadLocal {
    
    private static final ThreadLocal<DateFormat> tl = new ThreadLocal<DateFormat>(){
        
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyyMMdd");
        }
        
    };
    
    public static final Date convert(String source) throws ParseException{
        return tl.get().parse(source);
    }
}