package com.finance.common.core.utils;
import com.finance.common.core.constant.NoPrefixConstants;
import com.finance.common.core.text.UUID;
import cn.hutool.core.date.DateUtil;
import java.util.concurrent.atomic.AtomicInteger;
/**
* ID生成器工具类
*/
public class IdUtils {
private static final AtomicInteger MARK = new AtomicInteger(0);
private static final int MAX = 99999;
/**
* 获取自定义前缀的编号
*
* 【编号生成规则:SXSQ+YYYYMMDD(年月日)+5位流水号】
*/
public static String getCusNo(String prefix) {
String time = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
// 截取时间后5位
int last5 = Integer.parseInt(time.substring(time.length() - 6, time.length() - 1));
int currentMark;
do {
currentMark = MARK.get();
if (currentMark >= last5) {
last5 = currentMark + 1;
}
} while (!MARK.compareAndSet(currentMark, last5));
if (last5 > MAX) {
throw new RuntimeException("编号已经达到最大值");
}
return " (Thread ID: " + Thread.currentThread().getId() + ")" + prefix + time.substring(0, time.length() - 6) + last5;
}
public static void main(String[] args) {
Runnable runnable = () -> {
for (int i = 0; i < 10; i++) {
System.out.println(getCusNo(NoPrefixConstants.CREDIT_APPLY));
}
};
// 创建多个线程执行getCusNo方法
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
Thread thread3 = new Thread(runnable);
// 启动线程
thread1.start();
thread2.start();
thread3.start();
}
}
测试结果: