JavaSE 之 传统日期格式化的线程问题

Ella ·
更新时间:2024-11-01
· 897 次阅读

需求:让多线程同时去解析日期 错误示范 public class Test1 { @Test public void test01() throws Exception { //格式化日期类 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); //任务类:用于解析成Date对象 Callable task = new Callable() { @Override public Date call() throws Exception { return sdf.parse("20200123"); } }; //Date解析结果的集合 List<Future> list = new ArrayList(); //线程池 ExecutorService pool = Executors.newFixedThreadPool(10); for (int i = 1; i <= 10; i++) { Future future = pool.submit(task); list.add(future); } //打印结果 for (Future future : list) { System.out.println(future.get()); } //关闭线程池 pool.shutdown(); } } 正确示范 public class Test1 { @Test public void test01() throws Exception { //任务类:用于解析成Date对象 Callable task = new Callable() { @Override public Date call() throws Exception { return SimpleDateFormatThreadLocal.convert("20200123"); } }; //Date解析结果的集合 List<Future> list = new ArrayList(); //线程池 ExecutorService pool = Executors.newFixedThreadPool(10); for (int i = 1; i <= 10; i++) { Future future = pool.submit(task); list.add(future); } //打印结果 for (Future future : list) { System.out.println(future.get()); } //关闭线程池 pool.shutdown(); } } class SimpleDateFormatThreadLocal{ private static final ThreadLocal local = new ThreadLocal(){ //重写父类的方法:返回此线程局部变量的当前线程的“初始值”。 protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyyMMdd"); } }; public static Date convert(String str) throws ParseException{ SimpleDateFormat sdf = local.get(); Date date = sdf.parse(str); return date; } } JDK1.8后 正确示范 public class Test1 { @Test public void test01() throws Exception { //格式化日期类 DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd"); //任务类:用于解析成Date对象 Callable task = new Callable() { @Override public LocalDate call() throws Exception { return LocalDate.parse("20200123",dtf); } }; //Date解析结果的集合 List<Future> list = new ArrayList(); //线程池 ExecutorService pool = Executors.newFixedThreadPool(10); for (int i = 1; i <= 10; i++) { Future future = pool.submit(task); list.add(future); } //打印结果 for (Future future : list) { System.out.println(future.get()); } //关闭线程池 pool.shutdown(); } }
作者:晞晞奶爸



格式化 线程 javase

需要 登录 后方可回复, 如果你还没有账号请 注册新账号