扣扣技术分享交流群:1125844267
参考:java获取唯一时间戳Id.多线程保证唯一性_流年-CSDN博客
private static AtomicLong atomicTimeMills = new AtomicLong(0);
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
public static String getNextTime() { //并发获取不重复的时间
while (true) { //CAS思想
long currentMill = atomicTimeMills.get();
Long currentTimeMillis = Long.parseLong(LocalDateTime.now().format(formatter));
if (currentTimeMillis > currentMill && atomicTimeMills.compareAndSet(currentMill, currentTimeMillis)) {
return currentTimeMillis.toString();
}
}
}
public static void main(String[] args) {
for (int i = 0; i < 200; i++) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"开始获取时间");
System.out.println(Thread.currentThread().getName()+"当前时间:"+getNextTime());
System.out.println(Thread.currentThread().getName()+"获取时间执行完成");
}
}).start();
}
}