} catch (Exception e) { 
e.printStackTrace(); 



if (lastTimestamp == timestamp) { 
// 当前毫秒内,则+1 
sequence = (sequence + 1) & sequenceMask; 
if (sequence == 0) { 
// 当前毫秒内计数满了,则等待下一秒 
timestamp = tilNextMillis(lastTimestamp); 

} else { 
sequence = 0; 

lastTimestamp = timestamp; 
// ID偏移组合生成最终的ID,并返回ID 
long nextId = ((timestamp - twepoch) << timestampLeftShift) 
| (datacenterId << datacenterIdShift) 
| (workerId << workerIdShift) | sequence; 

return nextId; 


private long tilNextMillis(final long lastTimestamp) { 
long timestamp = this.timeGen(); 
while (timestamp <= lastTimestamp) { 
timestamp = this.timeGen(); 

return timestamp; 


private long timeGen() { 
return System.currentTimeMillis(); 



这种方式是一种比较高效的方式。也是twitter使用的一种方式。 

测试类:---------------------------------------------------------- 
import java.util.concurrent.BrokenBarrierException; 
import java.util.concurrent.CountDownLatch; 
import java.util.concurrent.CyclicBarrier; 
import java.util.concurrent.TimeUnit; 

public class IdWorkerTest { 
    public static void main(String []args){ 
        IdWorkerTest test = new IdWorkerTest(); 
        test.test2(); 
    } 

    public void test2(){ 
        final IdWorker w = new IdWorker(1,2); 
        final CyclicBarrier cdl = new CyclicBarrier(100); 

        for(int i = 0; i < 100; i++){ 
            new Thread(new Runnable() { 
                @Override 
                public void run() { 
                try { 
                    cdl.await(); 
                } catch (InterruptedException e) { 
                    e.printStackTrace(); 
                } catch (BrokenBarrierException e) { 
                    e.printStackTrace(); 
                } 
                System.out.println(w.nextId());} 
             }).start(); 
        } 
        try { 
            TimeUnit.SECONDS.sleep(5); 
        } catch (InterruptedException e) { 
           e.printStackTrace(); 
        } 

    } 
}

相关文章:

  • 2022-01-31
  • 2022-01-14
  • 2021-09-24
  • 2022-12-23
  • 2021-11-01
  • 2021-07-24
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-29
  • 2022-12-23
  • 2021-09-23
  • 2022-12-23
  • 2021-12-21
  • 2021-07-10
  • 2021-10-13
相关资源
相似解决方案