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

需求:让多线程同时去解析日期

错误示范

public class Test1 {
	@Test
	public void test01() throws Exception {

		//格式化日期类
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		//任务类:用于解析成Date对象
		Callable<Date> task = new Callable<Date>() {
			@Override
			public Date call() throws Exception {
				return sdf.parse("20200123");
			}
		};
		//Date解析结果的集合
		List<Future<Date>> list = new ArrayList<>();
		//线程池
		ExecutorService pool = Executors.newFixedThreadPool(10);
		for (int i = 1; i <= 10; i++) {
			Future<Date> future = pool.submit(task);
			list.add(future);
		}
		//打印结果
		for (Future<Date> future : list) {
			System.out.println(future.get());
		}
		//关闭线程池
		pool.shutdown();
	}
}

正确示范

public class Test1 {
	@Test
	public void test01() throws Exception {

		//任务类:用于解析成Date对象
		Callable<Date> task = new Callable<Date>() {
			@Override
			public Date call() throws Exception {
				return SimpleDateFormatThreadLocal.convert("20200123");
			}
		};

		//Date解析结果的集合
		List<Future<Date>> list = new ArrayList<>();

		//线程池
		ExecutorService pool = Executors.newFixedThreadPool(10);
		for (int i = 1; i <= 10; i++) {
			Future<Date> future = pool.submit(task);
			list.add(future);
		}
		//打印结果
		for (Future<Date> future : list) {
			System.out.println(future.get());
		}

		//关闭线程池
		pool.shutdown();
	}
}
class SimpleDateFormatThreadLocal{

	private static final ThreadLocal<SimpleDateFormat> local = new ThreadLocal<SimpleDateFormat>(){
		//重写父类的方法:返回此线程局部变量的当前线程的“初始值”。 
		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<LocalDate> task = new Callable<LocalDate>() {
			@Override
			public LocalDate call() throws Exception {
				return LocalDate.parse("20200123",dtf);
			}
		};
		//Date解析结果的集合
		List<Future<LocalDate>> list = new ArrayList<>();
		//线程池
		ExecutorService pool = Executors.newFixedThreadPool(10);
		for (int i = 1; i <= 10; i++) {
			Future<LocalDate> future = pool.submit(task);
			list.add(future);
		}
		//打印结果
		for (Future<LocalDate> future : list) {
			System.out.println(future.get());
		}
		//关闭线程池
		pool.shutdown();
	}
}
上一篇:网络通信中的线程池


下一篇:Dart3_异步编程