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

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

错误示范

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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();
}
}

正确示范

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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后 正确示范

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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();
}
}