16位随机数的组成:时间戳+自增长序列
时间戳长度为13位,自增长数字序列为1~999。由于后三位只能从1~999,所以在1ms内只能有999个不重复的随机数。1ms的并发数最大只能到999,如果对位数没有要求,可以多添加几位自增长序列,可以提高并发的数量。我做的业务,999的并发量足够使用。
代码如下:
public class Random { //private static int index = 0; static AtomicInteger index = new AtomicInteger(0); static Jedis jedis; public static void main(String[] args){ jedis =new Jedis("127.0.0.1", 6379);
new Thread(new Runnable() { @Override public void run() { while(true){ String timestamp = String.valueOf(new Date().getTime()); String key = timestamp + String.valueOf(new Random().getIndex()); System.out.println("1: " + key ); String value = getKey(key); if(value!= null){ System.out.println("key: " + key); index.set(1000); }else { setKey(key); } Thread.yield(); if(index.get() == 1000) break; } } }).start(); new Thread(new Runnable() { @Override public void run() { while(true){ String timestamp = String.valueOf(new Date().getTime()) ; String key = timestamp + String.valueOf(new Random().getIndex()); System.out.println("2: " + key ); String value = getKey(key); if(value!= null){ System.out.println("key: " + key); index.set(1000); }else{ setKey(key); } Thread.yield(); if(index.get() == 1000) break; } } }).start(); new Thread(new Runnable() { @Override public void run() { while(true){ String timestamp = String.valueOf(new Date().getTime()) ; String key = timestamp + String.valueOf(new Random().getIndex()); System.out.println("3: " + key ); String value = getKey(key); if(value!= null){ System.out.println("key: " + key); index.set(1000); }else{ setKey(key); } Thread.yield(); if(index.get() == 1000) break; } } }).start(); /*try { TimeUnit.MILLISECONDS.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("size: " + map.size());*/ } private String getIndex(){ synchronized(Random.class){ index.getAndIncrement(); if(index.get() == 1000) index.set(0); return String.format("%03d", index.get()); } } public static void setKey(String key){ synchronized(Random.class){ jedis.set(key, key); } } public static String getKey(String key){ synchronized(Random.class){ return jedis.get(key); } } }
代码使用三个线程模拟模拟请求,使用jredis 存储生成的数字,长时间运行来校验,是否会生成,重复的序列号。