使用java编写一个雪花算法
时间: 2024-04-29 10:25:04 浏览: 175
好的,下面是Java实现的雪花算法:
```java
import java.util.Random;
public class Snowflake {
private final long startTimeMillis;
private long lastTimestamp;
private long sequence;
public Snowflake() {
this.startTimeMillis = System.currentTimeMillis();
this.lastTimestamp = this.startTimeMillis;
this.sequence = new Random().nextInt(1000L);
}
public synchronized long nextId() {
long timestamp = System.currentTimeMillis();
if (timestamp < lastTimestamp) {
throw new RuntimeException("Clock moved backwards!");
}
if (timestamp == lastTimestamp) {
sequence = (sequence + 1) & (-1L ^ (-1L << 12));
if (sequence == 0) {
timestamp = waitNextMillis(timestamp);
}
} else {
sequence = new Random().nextInt(1000L);
}
lastTimestamp = timestamp;
long id = ((timestamp - startTimeMillis) << 22) | (sequence << 10) | new Random().nextInt(1024);
return id;
}
private long waitNextMillis(long timestamp) {
while (timestamp == lastTimestamp) {
timestamp = System.currentTimeMillis();
}
return timestamp;
}
}
```
希望对你有所帮助!
阅读全文