為了漸少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