Index: forgon-tools/src/test/java/com/forgon/tools/util/SimpleDateFormatThreadUnsafeTest.java =================================================================== diff -u -r41191 -r41337 --- forgon-tools/src/test/java/com/forgon/tools/util/SimpleDateFormatThreadUnsafeTest.java (.../SimpleDateFormatThreadUnsafeTest.java) (revision 41191) +++ forgon-tools/src/test/java/com/forgon/tools/util/SimpleDateFormatThreadUnsafeTest.java (.../SimpleDateFormatThreadUnsafeTest.java) (revision 41337) @@ -3,13 +3,16 @@ import org.junit.Test; import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class SimpleDateFormatThreadUnsafeTest { private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); @Test public void testThreadSafety() throws InterruptedException { @@ -20,8 +23,13 @@ executor.submit(() -> { try { // 多线程同时使用同一个 SimpleDateFormat 实例 - Date date = sdf.parse("2024-01-" + (index + 1)); - System.out.println(Thread.currentThread().getName() + ": " + date); + if (index < 9) { + Date date = sdf.parse("2024-01-0" + (index + 1)); + System.out.println(Thread.currentThread().getName() + ": " + ForgonDateUtils.safelyFormatDate(date, "yyyy-MM-dd", "1970-01-01")); + }else{ + Date date = sdf.parse("2024-01-" + (index + 1)); + System.out.println(Thread.currentThread().getName() + ": " + ForgonDateUtils.safelyFormatDate(date, "yyyy-MM-dd", "1970-01-01")); + } } catch (Exception e) { System.err.println(Thread.currentThread().getName() + " 出错: " + e.getMessage()); } @@ -31,4 +39,30 @@ executor.shutdown(); executor.awaitTermination(1, TimeUnit.MINUTES); } + + @Test + public void testDateFormatterSafety() throws InterruptedException { + ExecutorService executor = Executors.newFixedThreadPool(10); + + for (int i = 0; i < 10; i++) { + final int index = i; + executor.submit(() -> { + try { + // 多线程同时使用同一个 SimpleDateFormat 实例 + if (index < 9){ + LocalDate date = dateTimeFormatter.parse("2024-01-0" + (index + 1), LocalDate::from); + System.out.println(Thread.currentThread().getName() + ": " + date); + }else { + LocalDate date = dateTimeFormatter.parse("2024-01-" + (index + 1), LocalDate::from); + System.out.println(Thread.currentThread().getName() + ": " + date); + } + } catch (Exception e) { + System.err.println(Thread.currentThread().getName() + " 出错: " + e.getMessage()); + } + }); + } + + executor.shutdown(); + executor.awaitTermination(1, TimeUnit.MINUTES); + } }