彻底搞懂Java多线程(四)

时间:2022-11-26 10:52:31

SimpleDateFormat非线程安全问题

实现1000个线程的时间格式化

  1. package SimpleDateFormat;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. import java.util.concurrent.LinkedBlockingDeque;
  5. import java.util.concurrent.ThreadPoolExecutor;
  6. import java.util.concurrent.TimeUnit;
  7. /**
  8. * user:ypc;
  9. * date:2021-06-13;
  10. * time: 17:30;
  11. */
  12. public class SimpleDateFormat1 {
  13. private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
  14. public static void main(String[] args) {
  15. ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10,10,100,
  16. TimeUnit.MILLISECONDS,new LinkedBlockingDeque<>(1000),new ThreadPoolExecutor.DiscardPolicy());
  17.  
  18. for (int i = 0; i < 1001; i++) {
  19. int finalI = i;
  20. threadPoolExecutor.submit(new Runnable() {
  21. @Override
  22. public void run() {
  23. Date date = new Date(finalI * 1000);
  24. myFormatTime(date);
  25. }
  26. });
  27. }
  28. threadPoolExecutor.shutdown();
  29. }
  30. private static void myFormatTime(Date date){
  31. System.out.println(simpleDateFormat.format(date));
  32. }
  33. }

产生了线程不安全的问题