关于随机数
Math.random()
取值范围大于等于0.0且小于1.0的随机double值
Random的使用方式
for(int i = 0; i < 2; i++){ //创建2个随机数生成器 Random random = new Random(100); for(int j = 0; j < 3; j++){ //每个随机数生成器产生8个数 //n要返回的随机数的边界也就是随机数范围是0~50之间的整数 System.out.println(random.nextInt(50) + ","); } System.out.println(""); } /*----------------输出的结果--------------------------------- 15, 0, 24, 15, 0, 24, */
System.out.println("Random不含种子参数\n"); for(int i = 0; i < 2; i++){ //创建2个随机函数生成器 Random random = new Random(); for(int j = 0; j < 3; j++){ //每个随机数生成器产生3个数 //randmo.nextInt(50)代表生成的随机数范围是0~50,不会越界 System.out.println(random.nexInt(50) + ","); } System.out.println(""); } /*----------------输出的结果--------------------------------- 36, 7, 15, 33, 17, 13, */
由此可见,当使用参数的构造创建随机数生成器然后生成随机数序列的时候,产生的随机数是种子经过计算得到的,具有相同种子的Random对象生成的随机数序列相同,其次通过无参构造创建Random对象,种子是系统当前时间,因此创建的随机数是不相同的.
Math.random()和Random之间的关系
从Math类的源码就能看出Math.random()内部调用的方法就是Random类中的nextDouble()方法,此刻也就明确了文章一开始Math.random()返回的是double类型值
获得一个给定范围的随机整数
public static int getRandomNum(int SmallistNum, int BiggestNum){ Random random = new Random(); return (Math.abs(random.nextInt()) % (BiggestNum - SmallistNum + 1)) + SmallistNum; }
生成随机数 000~999 ,线程安全
//测试数据, if("1".equals(testData)) { DecimalFormat fmt2 = new DecimalFormat ("000"); AtomicInteger count = null; if(count == null || count.get() == 1000) { count = new AtomicInteger(1); } String countNumb = fmt2.format(count.getAndIncrement()); String surrentTime = Long.toString(System.currentTimeMillis()); //13位时间戳+机器编号+3位流水号 String traceId = surrentTime + machineNumb + countNumb; request.setAttribute("traceId", traceId); }