在 Java 開發中,隨機數的生成是常見需求,無論是驗證碼、測試數據、遊戲邏輯還是加密場景,都需要可靠的隨機數來源。Java 提供了多種生成隨機數的方式,各有優缺點與適用場景。本文將系統梳理三種核心方法:System.currentTimeMillis()、Math.random() 與 java.util.Random 類,並通過代碼示例展示如何正確獲取指定範圍的整數與浮點數,最後給出實際開發中的選型建議。
System.currentTimeMillis()此方法獲取當前時間與 UTC 1970-01-01 的毫秒差,返回 long 值。由於毫秒值不斷變化,可作為簡易隨機源。
final long timestamp = System.currentTimeMillis();
final int randomInt = (int) (timestamp % 100);
缺點:若在極短時間內連續調用,可能得到相同值;隨機性較弱,不適合安全敏感場景。
Math.random() 靜態方法Math.random() 返回 [0.0, 1.0) 區間的 double 值,底層實際調用 Random 類實例。
final double randomDouble = Math.random();
final int randomInt = (int) (randomDouble * 100);
注意:線程安全但效能一般,頻繁調用時建議改用 ThreadLocalRandom(Java 7+)。
java.util.Random 類(推薦)Random 類提供豐富的隨機數生成 API,支援多種基本類型,且可通過種子控制序列可重現性,適合單元測試與模擬場景。
// 默認種子(系統時間)
Random random = new Random();
// 指定種子,序列固定可復現
Random seededRandom = new Random(1000L);
| 方法 | 返回類型 | 範圍/說明 |
|---|---|---|
nextBoolean() | boolean | true/false 均勻分佈 |
nextInt() | int | 整個 int 範圍 |
nextInt(int bound) | int | [0, bound) 均勻分佈 |
nextLong() | long | 整個 long 範圍 |
nextFloat() | float | [0.0f, 1.0f) |
nextDouble() | double | [0.0, 1.0) |
nextGaussian() | double | 高斯分佈(均值 0,標準差 1) |
nextBytes(byte[]) | void | 填充位元組陣列 |
int randomInt = random.nextInt(100);
import java.util.Random;
import java.lang.Math;
public class RandomDecimalDemo {
public static float generate() {
Random r = new Random();
// 1. 先獲取 [0, 10) 浮點數
float raw = r.nextFloat() * 10;
// 2. 四捨五入保留兩位小數
float rounded = (float) (Math.floor(raw * 100 + 0.5) / 100);
// 3. 隨機決定正負
return r.nextBoolean() ? rounded : -rounded;
}
public static void main(String[] args) {
System.out.println(generate()); // 例:-3.14
}
}
import java.util.Random;
public class RandomTest {
public static void main(String[] args) {
// 1. System.currentTimeMillis()
long ts = System.currentTimeMillis();
System.out.printf("時間毫秒: %d, 取模100: %d%n", ts, ts % 100);
// 2. Math.random()
double d = Math.random();
System.out.printf("Math.random: %.4f, *100 取整: %d%n", d, (int)(d * 100));
// 3. Random 類(指定種子驗證可重現性)
Random r1 = new Random(1000);
Random r2 = new Random(1000);
System.out.println("相同種子首次 nextInt(100): " + r1.nextInt(100));
System.out.println("相同種子第二次 nextInt(100): " + r2.nextInt(100)); // 結果相同
// 默認種子每次不同
Random r3 = new Random();
Random r4 = new Random();
System.out.println("默認種子首次: " + r3.nextInt(100));
System.out.println("默認種子第二次: " + r4.nextInt(100)); // 大概率不同
}
}
Math.random() 最便捷。ThreadLocalRandom.current().nextInt(bound);Java 8+ 亦可用 SplittableRandom。new Random(seed)。java.security.SecureRandom。System.currentTimeMillis() 做業務隨機數,隨機性極差。掌握 Java 隨機數生成的原理與 API 差異,能讓你在不同業務場景下做出最優選擇。日常開發首推 Random 類或 ThreadLocalRandom,安全場景用 SecureRandom,切勿自造輪子。