为了渐少new 的次数而把SimpleDateFormat做成成员或者静态成员,但这样的做法是隐含着错误的,是不安全的。
对于这句话我写了个testcase,感觉单个进程下是没有问题的(网上大部分说这么写是有问题的,隐藏问题是什么,知道的同学说下?)。
public class hello{ public static void main(String[] arg) throws InterruptedException { Date date1 = new Date(); Date date2 = new Date(date1.getTime() + 1000 * 60 * 60 * 24); while (1 == 1) { if (!"2013-01-11".equals(method1(date1))) { System.out.println("error today:" + date1); } if (!"2013-01-12".equals(method2(date2))) { System.out.println("error tomorrow:" + date2); } Thread.sleep(1); } } private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); public static String method1(Date date) { return sdf.format(date); } public static String method2(Date date) { return sdf.format(date); } }
开一个线程也是没有问题的,只有开多个线程的情况下有问题。
public class hello{ public static void main(String[] arg) throws InterruptedException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date1 = new Date(); Date date2 = new Date(date1.getTime()+1000*60*60*24); System.out.println("date1:" + date1); System.out.println("date2:" + date2); Thread thread1 = new Thread(new Thread1(sdf,date1)); Thread thread2 = new Thread(new Thread2(sdf,date2)); thread1.start(); thread2.start(); //如果注释掉这行,是没有问题的 } } class Thread1 implements Runnable { private SimpleDateFormat sdf; private Date date; public Thread1(SimpleDateFormat sdf, Date date) { this.sdf = sdf; this.date = date; } public void run() { while(1==1) { String temp = sdf.format(date); if(!"2013-01-11".equals(temp)) { System.out.println("error today:" +date); System.exit(0); } else { System.out.println("ok1"); } } } } class Thread2 implements Runnable { private SimpleDateFormat sdf; private Date date; public Thread2(SimpleDateFormat sdf, Date date) { this.sdf = sdf; this.date = date; } public void run() { while(1==1) { String temp = sdf.format(date); if(!"2013-01-12".equals(temp)) { System.out.println("error tomorrow:" +date); System.exit(0); } else { System.out.println("ok2"); } } } }
运行结果是(出错):
date1:Fri Jan 11 11:26:29 CST 2013 date2:Sat Jan 12 11:26:29 CST 2013 ok1 ok1 ok1 ok1 error tomorrow:Sat Jan 12 11:26:29 CST 2013 ok1 ok1 ok1 ok1 ok1 ok1 ok1 ok1 ok1 ok1 ok1