zoukankan      html  css  js  c++  java
  • SimpleDateFormat的线程安全问题与解决方案

    SimpleDateFormat 是 Java 中一个常用的类,该类用来对日期字符串进行解析和格式化输出,但如果使用不小心会导致非常微妙和难以调试的问题.

    因为 DateFormat 和 SimpleDateFormat 类不都是线程安全的,在多线程环境下调用 format() 和 parse() 方法应该使用同步代码来避免问题,
    或者使用ThreadLocal, 也是将共享变量变为独享,线程独享肯定能比方法独享在并发环境中能减少不少创建对象的开销。
    如果对性能要求比较高的情况下,一般推荐使用这种方法。

     1 public class DateUtil {
     2 
     3     static final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     4 
     5     static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
     6         protected DateFormat initialValue() {
     7             return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     8         }
     9     };
    10 
    11     private static DateFormat dateFormat() {
    12         // return sdf;
    13         return threadLocal.get();
    14     }
    15 
    16     public static Date parse(String dateStr) throws ParseException {
    17         return dateFormat().parse(dateStr);
    18     }
    19 
    20     public static String format(Date date) {
    21         return dateFormat().format(date);
    22     }
    23 
    24     public static void main(String[] args) {
    25         for (int i = 0; i < 3; i++) {
    26             new Thread() {
    27                 public void run() {
    28                     while (true) {
    29                         try {
    30                             Thread.sleep(2000);
    31                         } catch (InterruptedException e1) {
    32                             e1.printStackTrace();
    33                         }
    34                         
    35                         try {
    36                             System.out.println(this.getName() + ":" + DateUtil.parse("2013-05-24 06:02:20"));
    37                         } catch (ParseException e) {
    38                             e.printStackTrace();
    39                         }
    40                     }
    41                 }
    42             }.start();
    43         }
    44     }

    参考:

    http://www.cnblogs.com/zemliu/p/3290585.html

    http://www.cnblogs.com/peida/archive/2013/05/31/3070790.html

  • 相关阅读:
    android 图片全屏
    .9.png
    C++中的endl
    C++输入输出cin与cout
    word-search
    Java中的的画正三角方法
    octave中的一些基本操作
    C#中判断语句 if、if-else if、switch-case
    C#中的异常处理(try-catch的使用)——使程序更加稳定
    编程&blog处女篇-用C#求100以内的质数
  • 原文地址:https://www.cnblogs.com/kofxxf/p/3972727.html
Copyright © 2011-2022 走看看