LBalloonFlower 2019-09-15 11:39 采纳率: 0%
浏览 282

存在线程安全问题怎么修改bug

public class App {

    public static void main( String[] args )
    {
        ExecutorService executorService = Executors.newCachedThreadPool();
        List<String> dateStrList = Lists.newArrayList(
                "2018-04-01 10:00:01",
                "2018-04-02 11:00:02",
                "2018-04-03 12:00:03",
                "2018-04-04 13:00:04",
                "2018-04-05 14:00:05"
        );
        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        for (final String str : dateStrList) {
            executorService.execute(new Runnable() {

                public void run() {
                    // TODO Auto-generated method stub
                    try {
                        System.out.println(simpleDateFormat.parse(str));
                        TimeUnit.SECONDS.sleep(1);
                    } catch ( Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            });

        }

    }
}
  • 写回答

2条回答 默认 最新

  • Z小繁 博客专家认证 2019-09-15 13:27
    关注

    SimpleDateFormat是线程不安全的,需放在run()方法内部。或者考虑使用threadlocal封装,可参考 DateUtil
    https://github.com/zxiaofan/JavaUtils/blob/master/src/com/zxiaofan/util/other/DateUtil.java

    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?