服务器唯一id生成规则

      在使用hashCode的时候,发现会出现相同id,虽然几率很小。虽然发现并不是hashCode的原因,而是其他逻辑的问题。

  但是还是试着自己写了一个id生成器,有些id是int的,比如说任务id;有些id是long的,比如说玩家id。

先贴代码来看:

服务器唯一id生成规则
private static AtomicInteger id = new AtomicInteger(0);

    

    public static long getId()

    {

        return (ServerKit.getServerId() & 0xFFFF) << 48 | (System.currentTimeMillis()/1000L & 0xFFFFFFFF) << 16 | id.addAndGet(1) & 0xFFFF;

    }

    

    private static AtomicInteger IntId = new AtomicInteger(0);

    

    public static int getIntId()

    {

        return ((int)(System.currentTimeMillis() - 1000000000000L)/1000)<<16L | (IntId.addAndGet(1));

    }
View Code

      在生成玩家id的时候把服务器的id也参与,便于以后的合服。

      因为服务器是多线程,所以就用了 AtomicInteger 类型,不用再使用类似 sync等同步工具。

你可能感兴趣的:(服务器)