SimpleDateFormat的使用以及注意事项

来源:互联网 发布:maxdos网络克隆工具 编辑:程序博客网 时间:2024/06/13 01:59

1.SimpleDateFormat是线程不安全的

如下代码在单线程的环境是安全的但是在多线程的环境中绝对是不安全的

public class SimpleDateFormatTest {private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");public void format1(){sdf.format(new Date());}public void format2(){sdf.format(new Date());}}

接下来证明它不是线程安全的:
package org.sh.testpaper;import java.text.SimpleDateFormat;import java.util.Date;public class SimpleDateFormatTest {public static void main(String[] args) {Date date1 = new Date();Date date2 = new Date(date1.getTime()+1000*24*60*60);System.out.println("date1="+date1);System.out.println("date2="+date2);SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");SDFThread1 s1 = new SDFThread1(sdf, date1);SDFThread2 s2 = new SDFThread2(sdf, date2);new Thread(s1).start();new Thread(s2).start();}}class SDFThread1 implements Runnable{private SimpleDateFormat sdf ;private Date date;public SDFThread1(SimpleDateFormat sdf,Date date){this.sdf = sdf;this.date = date;}@Overridepublic void run() {while(true){String strDate = sdf.format(date);System.out.println("thread1:"+strDate);if("2014-05-05".equals(strDate)){System.out.println("Error:"+strDate);System.exit(0);}}}}class SDFThread2 implements Runnable{private SimpleDateFormat sdf ;private Date date;public SDFThread2(SimpleDateFormat sdf,Date date){this.sdf = sdf;this.date = date;}@Overridepublic void run() {while(true){String strDate = sdf.format(date);System.out.println("thread2:"+strDate);if("2014-05-04".equals(strDate)){System.out.println("Error:date1"+strDate);System.exit(0);}}}}

测试结果:

date1=Sun May 04 20:08:46 CST 2014date2=Mon May 05 20:08:46 CST 2014thread1:2014-05-05thread2:2014-05-05Error:2014-05-05thread2:2014-05-05thread2:2014-05-05thread2:2014-05-05thread2:2014-05-05thread2:2014-05-05

从测试结果可以看出SimpleDateFormat是线程不安全的。


0 0
原创粉丝点击