码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-11-16 00:54:35      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:private   shutdown   环境   string   i++   public   解决方案   parse   info   

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、执行结果如下:

技术图片

 

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

 

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

标签:private   shutdown   环境   string   i++   public   解决方案   parse   info   

原文地址:https://www.cnblogs.com/zhanh247/p/11870036.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!