package com.a.mq.t;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SimpleDateFormatThreadLocal {
static class ThreadSafeDateFormat {
public static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal = ThreadLocal.withInitial(
() -> {
System.out.println(Thread.currentThread().getName() + "创建");
return new SimpleDateFormat("mm:ss");
});
}
public static ExecutorService pool = Executors.newFixedThreadPool(16);
public static void main(String[] args) {
for (int i=0; i<1000; i++) {
int finalI = i;
pool.submit(() -> {
String date = new SimpleDateFormatThreadLocal().date(finalI);
System.out.println(date);
});
}
pool.shutdown();
}
private String date(int seconds) {
Date date = new Date(1000 * seconds);
SimpleDateFormat simpleDateFormat = ThreadSafeDateFormat.dateFormatThreadLocal.get();
return simpleDateFormat.format(date);
}
}