方法 1:使用 ThreadLocalRandom(推荐,Java 7+)
ThreadLocalRandom 是 Java 7 引入的线程安全的随机数生成器,性能优于 Random。
import java.util.concurrent.ThreadLocalRandom;
public class RandomNumberExample {
public static void main(String[] args) {
// 生成 1 到 10 的随机数(包含 1 和 10)
int randomNumber = ThreadLocalRandom.current().nextInt(1, 11);
System.out.println("随机数: " + randomNumber);
}
}
说明:
nextInt(origin, bound)生成[origin, bound)区间的随机数,即包含origin但不包含bound。- 要包含
10,需将上界设为11。
方法 2:使用 Random 类(传统方式)
java.util.Random 是经典的随机数生成器,适用于简单场景。
import java.util.Random;
public class RandomNumberExample {
public static void main(String[] args) {
Random random = new Random();
// 生成 1 到 10 的随机数(包含 1 和 10)
int randomNumber = random.nextInt(10) + 1;
System.out.println("随机数: " + randomNumber);
}
}
说明:
nextInt(10)生成[0, 9]的随机数,加1后得到[1, 10]。
方法 3:使用 Math.random()(简单但性能较低)
Math.random() 返回 [0.0, 1.0) 的 double 值,需手动转换。
public class RandomNumberExample {
public static void main(String[] args) {
// 生成 1 到 10 的随机数(包含 1 和 10)
int randomNumber = (int)(Math.random() * 10) + 1;
System.out.println("随机数: " + randomNumber);
}
}
说明:
Math.random() * 10生成[0.0, 10.0),强转后为[0, 9],加1得到[1, 10]。
方法 4:使用 SecureRandom(加密安全场景)
如果需要高安全性(如生成验证码、密钥等),应使用 SecureRandom。
import java.security.SecureRandom;
public class RandomNumberExample {
public static void main(String[] args) {
SecureRandom secureRandom = new SecureRandom();
int randomNumber = secureRandom.nextInt(10) + 1;
System.out.println("随机数: " + randomNumber);
}
}
说明:
SecureRandom生成更随机的数,但性能较低,不适用于高频场景。
| 方法 | 适用场景 | 特点 |
|---|---|---|
ThreadLocalRandom |
多线程环境(推荐) | 高性能,线程安全 |
Random |
单线程简单场景 | 经典方式,性能较好 |
Math.random() |
简单场景(不推荐高频使用) | 代码简洁,但性能较低 |
SecureRandom |
安全敏感场景(如加密) | 高安全性,性能较低 |
根据需求选择合适的方法,大多数情况下推荐 ThreadLocalRandom。
