需求:让多线程同时去解析日期
错误示范
public class Test1 {
@Test
public void test01() throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Callable<Date> task = new Callable<Date>() {
@Override
public Date call() throws Exception {
return sdf.parse("20200123");
}
};
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 {
Callable<Date> task = new Callable<Date>() {
@Override
public Date call() throws Exception {
return SimpleDateFormatThreadLocal.convert("20200123");
}
};
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");
Callable<LocalDate> task = new Callable<LocalDate>() {
@Override
public LocalDate call() throws Exception {
return LocalDate.parse("20200123",dtf);
}
};
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();
}
}