博客
关于我
为什么说SimpleDateFormat是线程不安全的?
阅读量:264 次
发布时间:2019-02-28

本文共 1453 字,大约阅读时间需要 4 分钟。

演示SimpleDateFormat是线程不安全的的示例代码

public class SpringbootApplication {           static ExecutorService executorService = Executors.newFixedThreadPool(10);    //SimpleDateFormat    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    //搞个set,去重做个数据统计    static Set
set = new HashSet(); //测试的方法 public static String addDate(int seconds) { Date date = new Date(1000 * seconds); String result = sdf.format(date); return result; } } public static void main(String[] args) throws Exception { for (int i = 0; i < 100; i++) { int a = i; executorService.execute(new Runnable() { @Override public void run() { String result = addDate(a); System.out.println(result); set.add(result); } }); } //给个5秒的休眠期,方便子线程都运行完 TimeUnit.SECONDS.sleep(5); System.out.println(set.size()); }}

运行结果:

在这里插入图片描述

在这里插入图片描述

可以发现,运行了2次,set集合里面的数目都是不同的,每次运行的结果都不同,这肯定说不上是线程安全。

在方法里加个synchronized关键字再试试:

public static String addDate(int seconds) {           Date date = new Date(1000 * seconds);        synchronized (SpringbootApplication.class) {               String result = sdf.format(date);            return result;        }    }

在这里插入图片描述

在这里插入图片描述

运行了两次,set集合里面的数目都是100,和我们循环的次数是一样的,符合预期。

总结

通过多次的运行结果,以及加上synchronized关键字后的效果比较,可以确定SimpleDateFormat是线程不安全的。

转载地址:http://adjp.baihongyu.com/

你可能感兴趣的文章
ndarray 比 recarray 访问快吗?
查看>>
ndk-cmake
查看>>
NdkBootPicker 使用与安装指南
查看>>
ndk特定版本下载
查看>>
NDK编译错误expected specifier-qualifier-list before...
查看>>
Neat Stuff to Do in List Controls Using Custom Draw
查看>>
Necurs僵尸网络攻击美国金融机构 利用Trickbot银行木马窃取账户信息和欺诈
查看>>
Needle in a haystack: efficient storage of billions of photos 【转】
查看>>
NeHe OpenGL教程 07 纹理过滤、应用光照
查看>>
NeHe OpenGL教程 第四十四课:3D光晕
查看>>
Neighbor2Neighbor 开源项目教程
查看>>
neo4j图形数据库Java应用
查看>>
Neo4j图数据库_web页面关闭登录实现免登陆访问_常用的cypher语句_删除_查询_创建关系图谱---Neo4j图数据库工作笔记0013
查看>>
Neo4j图数据库的介绍_图数据库结构_节点_关系_属性_数据---Neo4j图数据库工作笔记0001
查看>>
Neo4j图数据库的数据模型_包括节点_属性_数据_关系---Neo4j图数据库工作笔记0002
查看>>
Neo4j安装部署及使用
查看>>
Neo4j电影关系图Cypher
查看>>
Neo4j的安装与使用
查看>>
Neo4j(1):图数据库Neo4j介绍
查看>>
Neo4j(2):环境搭建
查看>>