Java生成11位的纯数字非0开头的唯一userid
时间: 2024-03-15 14:47:22 浏览: 96
java语言生成唯一ID的方法
以下是使用Java实现生成11位纯数字非0开头的唯一userID的示例代码:
```java
import java.util.concurrent.atomic.AtomicLong;
public class UniqueIDGenerator {
private static final int MACHINE_ID = 1; // 机器ID
private static final long START_TIMESTAMP = 1577808000000L; // 起始时间戳(2020-01-01 00:00:00)
private static final int SEQUENCE_BITS = 12; // 序列号占用的位数
private static final int MAX_SEQUENCE = (1 << SEQUENCE_BITS) - 1; // 序列号最大值
private static final int MACHINE_BITS = 10; // 机器ID占用的位数
private static final int MACHINE_SHIFT = SEQUENCE_BITS; // 机器ID左移位数
private static final int TIMESTAMP_SHIFT = MACHINE_BITS + SEQUENCE_BITS; // 时间戳左移位数
private static final AtomicLong SEQUENCE = new AtomicLong(0); // 序列号生成器
private static long lastTimestamp = 0; // 上次生成ID的时间戳
public static long generateUserID() {
while (true) {
long timestamp = System.currentTimeMillis();
if (timestamp < lastTimestamp) {
throw new RuntimeException("Clock moved backwards");
} else if (timestamp == lastTimestamp) {
long sequence = SEQUENCE.incrementAndGet() & MAX_SEQUENCE;
if (sequence == 0) {
timestamp = waitNextMillis(lastTimestamp);
}
lastTimestamp = timestamp;
long userID = (timestamp - START_TIMESTAMP) << TIMESTAMP_SHIFT | MACHINE_ID << MACHINE_SHIFT | sequence;
if (String.valueOf(userID).charAt(0) != '0') {
return userID;
}
} else {
SEQUENCE.set(0);
lastTimestamp = timestamp;
}
}
}
private static long waitNextMillis(long lastTimestamp) {
long timestamp = System.currentTimeMillis();
while (timestamp <= lastTimestamp) {
timestamp = System.currentTimeMillis();
}
return timestamp;
}
}
```
该代码使用AtomicLong类型的SEQUENCE变量作为序列号生成器,同时使用AtomicLong的incrementAndGet方法实现线程安全的序列号生成。使用AtomicLong类型的变量可以避免多线程竞争导致的序列号重复问题。在生成唯一ID的过程中,如果开头为0,则重新生成ID,直到生成的ID符合要求为止。由于使用了Snowflake算法,生成的ID是唯一的,并且按照时间顺序递增。
阅读全文