`

Format的子类中SimpleDateFormat,NumberFormat,MessageFormat那些是线程安全的

    博客分类:
  • java
阅读更多
SimpleDateFormat,NumberFormat,MessageFormat这三个类都是Format的之类,其中SimpleDateFormat,MessageFormat不是线程安全的,所以在类中不要应用它作为静态类变量,只能用他做方法的局部变量才是线程安全的,不过MessageFormat是线程安全的,
public class TestDateFormat {
public static DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

public String getTime(Date date){
return df.format(date);
}

public static void main(String[] args) throws InterruptedException {
TestDateFormat tdf = new TestDateFormat();
TestClient tc1 = new TestClient(tdf);
TestClient tc2 = new TestClient(tdf);
tc1.start();
// tc1.sleep(3000);
tc2.start();
}

private static class TestClient extends Thread{
TestDateFormat tdf = null;
public TestClient(TestDateFormat tdf){
this.tdf = tdf;
}
@Override
public void run() {
try {
Thread.currentThread().sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("thread"+Thread.currentThread().getName()+":"+tdf.getTime(new Date()));
}
}
}


看来以后要写出线程安全的类,不要用全局变量了,用方法传值获取数据,最稳妥
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics