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()));
}
}
}
看来以后要写出线程安全的类,不要用全局变量了,用方法传值获取数据,最稳妥
分享到:
相关推荐
目录SimpleDateFormat诡异bug复现SimpleDateFormat诡异bug字符串日期转Date日期(parse)Date日期转String类型(format)SimpleDateFormat出现bug的原因如何解决SimpleDateFormat多线程安全问题局部变量使用...
NULL 博文链接:https://flynndang.iteye.com/blog/711878
使用一个类的时候我们必须先弄清楚这个类是否是线程安全的。...一般来说,Java标准库中的类在其API文档中会说明其是否是线程安全的(没有说明其是否是线程安全的,则可能是也可能不是线程安全的)。
高并发之-SimpleDateFormat类的线程安全问题和解决方案.docx
关于SimpleDateFormat的非线程安全问题及其解决方案.docx
主要介绍了SimpleDateFormat的线程安全问题与解决方案,非常不错,具有参考借鉴价值,需要的朋友可以参考下
SimpleDateFormat线程不安全的5种解决方案.md
SimpleDateFormat线程不安全的5种解决方案.docx
SimpleDateFormat 是 Java 中一个非常常用的类,该类用来对日期字符串进行解析和格式化输出,但如果使用不小心会导致非常微妙和难以调试的问题,因为 DateFormat 和 SimpleDateFormat 类不都是线程安全的,在多线程...
JavaScript实现的java.text.SimpleDateFormat。希望多多交流。
主要介绍了Java SimpleDateFormat线程安全问题原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); date.setTime(time); System.out.println(sdf.format(date)); 发现时间于想要的时间不符,请运行Time.reg文件
主要介绍了Java多线程环境下SimpleDateFormat类安全转换,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
NULL 博文链接:https://chaoyi.iteye.com/blog/2082317
有关SimpleDateFormat的常用方法说明
SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); Long time=new Long(445555555); String d = format.format(time); Date date=format.parse(d); System.out.println("Format ...
日期操作。。。基础的SimpleDateFormat格式化日期!!操作!》初级学习代码
主要为大家详细介绍了Java中SimpleDateFormat的使用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
由浅入深解析 SimpleDateFormat 由浅入深解析 SimpleDateFormat