多线程下 SimpleDateFormat

Posted 斌灬小生不才

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程下 SimpleDateFormat相关的知识,希望对你有一定的参考价值。

package com.shob.tt.single;

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

public class StringUtil {

	/**
	 * SimpleDateFormat在多线程环境下容易造成数据转换及处理数据的不准确
	 * 处理方式:创建多个SimpleDateFormat
	 * @param formatPattern
	 * @param dateString
	 * @return
	 * @throws ParseException
	 */
	public static Date parse(String formatPattern,String dateString) throws ParseException{
		return new SimpleDateFormat(formatPattern).parse(dateString);
	}
	
	public static String format(String formatPattern,Date date) throws ParseException{
		return new SimpleDateFormat(formatPattern).format(date);
	}
	
	private static ThreadLocal<SimpleDateFormat> tl = new ThreadLocal<SimpleDateFormat>();
	/**
	 * ThreadLocal 类能使线程绑定到指定对象
	 * @param formatPattern
	 * @return
	 */
	public static SimpleDateFormat getSimpleDateFormat(String formatPattern){
		SimpleDateFormat sdf = null;
		sdf = tl.get();
		if(null == sdf){
			sdf = new SimpleDateFormat(formatPattern);
			tl.set(sdf);
		}
		return sdf;
	}
}

  

以上是关于多线程下 SimpleDateFormat的主要内容,如果未能解决你的问题,请参考以下文章

Java多线程:SimpleDateFormat

案例-- 线程不安全对象(SimpleDateFormat)

SimpleDateFormat时间格式化存在线程安全问题

1.1多线程上下文切换

(转)关于SimpleDateFormat安全的时间格式化线程安全问题

Java-JUC(十四):SimpleDateFormat是线程不安全的