栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

simpleDateFormat线程不安全

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

simpleDateFormat线程不安全

一、为什么线程不安全

SimpleDateFormat被定义为static,那么多个线程共用,就会导致线程不安全,但是SimpleDateFormat被声明局部变量,一个线程使用一个SimpleDateFormat就不会导致线程不安全

二、如何线程才安全,推荐使用ThreadLocal
package com.example.dateTest;

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


public class ThreadLocalDateUtil {

    private static final String date_format = "yyyy-MM-dd HH:mm:ss";
    private static ThreadLocal threadLocal = new ThreadLocal();

    public static DateFormat getDateFormat() {
        DateFormat df = threadLocal.get();
        if (df == null) {
            df = new SimpleDateFormat(date_format);
            threadLocal.set(df);
        }
        return df;
    }

    public static String formatDate(Date date){
        String result = "";
        try {
            result = getDateFormat().format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static Date parse(String strDate){
        Date resultDate = null;
        try {
            resultDate = getDateFormat().parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return resultDate;
    }
}
三、学习threadLocal很有意思

threadLocal用来多线程隔离数据,很有意思的一个知识点,可以学习下。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/489991.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号