本文共 1296 字,大约阅读时间需要 4 分钟。
以下是一个演示SimpleDateFormat线程不安全性的Java代码示例。该代码使用多线程环境下 SimpleDateFormat 的一个潜在问题,展示了其线程不安全性。
public class SpringbootApplication { static ExecutorService executorService = Executors.newFixedThreadPool(10); static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); static Set set = new HashSet<>(); public static String addDate(int seconds) { Date date = new Date(1000 * seconds); synchronized (SpringbootApplication.class) { 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); set.add(result); } }); } TimeUnit.SECONDS.sleep(5); System.out.println(set.size()); }} 在未加锁之前,运行该代码会得到以下结果:
运行2次,集合中包含2个不同的元素。
每次运行的结果都不同,这表明 SimpleDateFormat 在多线程环境下可能存在线程安全问题。
当在 addDate 方法中添加 synchronized 键字后,运行结果如下:
运行2次,集合中包含100个不同的元素。
结果与循环次数一致,表明锁有效地确保了线程安全。
通过多次运行和对比加锁前后的效果,可以确认SimpleDateFormat在多线程环境下存在线程不安全问题。使用 synchronized 键字可以有效地解决该问题。
转载地址:http://adjp.baihongyu.com/