SimpleDateFormat线程不安全问题
来源:互联网 发布:数据库过滤器 编辑:程序博客网 时间:2024/06/05 20:05
导致SimpleDateFormat出现多线程安全问题的原因,是因为:SimpleDateFormat处理复杂,Jdk的实现中使用了成员变量来传递参数,这就造成在多线程的时候会出现错误
一些常见的错误代码大致如下
public class DateFormatTest { private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); xxxxxx...}
错误浮现dmo
最笨的解决办法:不使用static SimpleDateFormat,每次使用都直接new一个package dateFormat;import java.text.SimpleDateFormat;import java.util.Date;public class DateFormatTest { private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); public static void main(String[] args) { Date today = new Date(); Date tomorrow = new Date(today.getTime() + 1000 * 60 * 60 * 24); System.out.println(today); System.out.println(tomorrow); Thread thread1 = new Thread(new Thread1(dateFormat, today)); thread1.start(); Thread thread2 = new Thread(new Thread2(dateFormat, tomorrow)); thread2.start(); }}class Thread1 implements Runnable { private SimpleDateFormat dateFormat; private Date date; public Thread1(SimpleDateFormat dateFormat, Date date) { this.dateFormat = dateFormat; this.date = date; } public void run() { for (;;) { System.out.println("Thread1.run" + date); String strDate = dateFormat.format(date); if (!"2015-11-03".equals(strDate)) { System.err.println("today=" + strDate); System.exit(0); } } }}class Thread2 implements Runnable { private SimpleDateFormat dateFormat; private Date date; public Thread2(SimpleDateFormat dateFormat, Date date) { this.dateFormat = dateFormat; this.date = date; } public void run() { for (;;) { System.out.println("Thread2.run" + date); String strDate = dateFormat.format(date); if (!"2015-11-04".equals(strDate)) { System.err.println("tomorrow=" + strDate); System.exit(0); } } }}
比较高大上的解决办法joda
0 0
- SimpleDateFormat线程不安全问题
- Java SimpleDateFormat 线程不安全问题及解决方法
- java SimpleDateFormat线程不安全
- SimpleDateFormat 线程不安全
- SimpleDateFormat线程不安全
- simpledateformat线程不安全解决方案
- SimpleDateFormat线程不安全
- SimpleDateFormat线程不安全
- simpledateformat线程不安全解决方案
- SimpleDateFormat线程不安全 【坑】
- SimpleDateFormat非线程不安全
- 解决SimpleDateFormat的线程不安全问题的方法:ThreadLocal
- Java之——SimpleDateFormat 线程不安全问题及解决方法
- SimpleDateFormat线程不安全及解决办法
- SimpleDateFormat线程不安全及解决办法
- SimpleDateFormat线程不安全及解决办法
- SimpleDateFormat线程不安全及解决办法
- HashMap线程不安全问题
- Defer, Panic, and Recover
- POP到指定的界面
- 鸟哥的Linux私房菜(基础篇)-第一章、Linux是什么(一.1.Linux是什么)
- iOS9 适配
- FFMPeg-ios编译
- SimpleDateFormat线程不安全问题
- hiho1082 : 然而沼跃鱼早就看穿了一切
- node install for linux
- 鸟哥的Linux私房菜(基础篇)-第一章、Linux是什么(一.2. Torvalds的Linux发展)
- Foreach用法
- git 使用新手大坑
- 鸟哥的Linux私房菜(基础篇)-第一章、Linux是什么(一.3. Linux的特色)
- XCode: 如何添加自定义代码片段
- sublime text 3 c/c++(11) 以及sublimeclang配置 windows