这里写了三个随机生成6位数字的方法,效率有所不同,其中ThreadLocalRandom表现极佳。
话不多说,直接上代码
public class RandomVerificationCodeDemo {
public static void main(String[] args) {
//循环次数
int count = 100000000;
test1(count);
test2(count);
test3(count);
}
/**
* Math.random()方法
* 返回一个带有正号的{@code双精度}值,该值大于或等于{@code 0.0}且小于{@code 1.0}。
* 返回值是在该范围内(近似)均匀分布的伪随机选择的。(例如: 0.9670743674319628; 0.18936001981929507)
*
* 效率比截取字符串生成6位数高
*
* */
public static void test1(int count) {
long startTime = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
int number = (int) ((Math.random() * 9 + 1) * 100000);
}
long endTime = System.currentTimeMillis();
System.out.println("Math.random()方法耗时:" + (endTime - startTime));
}
/**
* 使用Random.nextInt()方法
* 返回一个伪随机的,均匀分布的{@code int}值,介于0(包括)和指定的值(不包括)之间,
* 从这个随机数生成器的序列中提取。
*
* 效率比Math.random()高,仅次于ThreadLocalRandom.nextInt()方法
*
*
* */
public static void test2(int count) {
int min = 100000; // 最小值为10万
int max = 999999; // 最大值为999999
long startTime = System.currentTimeMillis();
Random random = new Random();
for (int i = 0; i < count; i++) {
int number = random.nextInt((max - min + 1)) + min;
}
long endTime = System.currentTimeMillis();
System.out.println("Random.nextInt()方法耗时:" + (endTime - startTime));
}
/**
* ThreadLocalRandom.current().nextInt()方法
* 返回一个介于指定的原点(包括)和指定的边界(不包括)之间的伪随机{@code int}值
* ThreadLocalRandom是Java 8中引入的一个新特性,它提供了线程局部的随机数生成器,
* 相比于Random,它在多线程环境下有更好的性能表现
*
* 效率最高,且多线程中常用
*
* */
public static void test3(int count) {
int min = 100000; // 最小值为10万
int max = 999999; // 最大值为999999
long startTime = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
int number = ThreadLocalRandom.current().nextInt(min, max + 1);
}
long endTime = System.currentTimeMillis();
System.out.println("ThreadLocalRandom.current().nextInt()方法:" + (endTime - startTime));
}
}
方法一:
Math.random()方法
返回一个带有正号的{@code双精度}值,该值大于或等于{@code 0.0}且小于{@code 1.0}。返回值是在该范围内(近似)均匀分布的伪随机选择的。(例如: 0.9670743674319628; 0.18936001981929507) 效率比直接截取字符串生成6位数高
方法二:
Random.nextInt()方法
返回一个伪随机的,均匀分布的{@code int}值,介于0(包括)和指定的值(不包括)之间,从这个随机数生成器的序列中提取。 效率比Math.random()高,仅次于ThreadLocalRandom.nextInt()方法
方法三:
ThreadLocalRandom.current().nextInt()方法
返回一个介于指定的原点(包括)和指定的边界(不包括)之间的伪随机{@code int} 值ThreadLocalRandom是Java 8中引入的一个新特性,它提供了线程局部的随机数生成器,相比于Random,它在多线程环境下有更好的性能表现 效率最高,且多线程中常用
其中还有通过字符串截取位数或者其他的方法生成我就不在这里一一列出了。
创作不易,你的点赞+收藏才是我的动力☺