zoukankan      html  css  js  c++  java
  • 并发条件下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、执行结果如下:

     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);
        }
    }
  • 相关阅读:
    Android ble 蓝牙4.0 总结
    Java byte数据类型详解
    Cocos2d-X在SwitchControl使用
    【翻译mos文章】Linux x86 and x86-64 系统SHMMAX最大
    poj 2478 Farey Sequence(欧拉函数是基于寻求筛法素数)
    Akka FSM 源代码分析
    HDU 4828 (卡特兰数+逆)
    [JSP][JSTL]页面调用函数--它${fn:}内置函数、是推断字符串是空的、更换车厢
    android 中国通信乱码问题
    Recall(检出率)和 Precision(准确性)
  • 原文地址:https://www.cnblogs.com/zhanh247/p/11870036.html
Copyright © 2011-2022 走看看