传统时间格式化的线程安全问题
在使用SimpleDateFormat时间格式处理类会出现线程安全问题,而java8新特性中的 DateTimeFormatter时间格式处理类解决了此问题,代码如下:
@Test
public static void main(String[] args)throws Exception {
//出现线程安全问题:异常信息为java.lang.NumberFormatException: For input string: ".22E1.22E1"
/* SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Callable<Date> callable = new Callable<Date>() {
@Override
public Date call() throws Exception {
return sdf.parse("20200220");
}
};*/
//加锁后操作
/* Callable<Date> callable = new Callable<Date>() {
@Override
public Date call() throws Exception {
return DateFormatThreadLocal.convert("20200220");
}
};*/
//java8时间处理类
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
Callable<LocalDate> callable = new Callable<LocalDate>() {
@Override
public LocalDate call() throws Exception {
return LocalDate.parse("20200220",dtf);
}
};
ExecutorService pool = Executors.newFixedThreadPool(10);
List<Future<LocalDate>> futures = new ArrayList<>();
for (int i = 0; i < 10; i++) {
futures.add(pool.submit(callable));
}
for (Future<LocalDate> future : futures) {
System.out.println(future.get());
}
pool.shutdown();
}
//加锁
class DateFormatThreadLocal{
private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>(){
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyyMMdd");
}
};
public static Date convert(String source) throws ParseException {
return df.get().parse(source);
}
计算两个"时间"之间的间隔
@Test
public static void main(String[] args)throws Exception {
Instant ins1 = Instant.now();
Thread.sleep(10000);
Instant ins2 = Instant.now();
Duration durantion = Duration.between(ins1, ins2);
System.out.println(durantion.toMillis());//10000毫秒
}