java.lang.Math.random() 無需導包,返回 double 範圍 [0.0, 1.0)。常用變換:
int n = (int)(Math.random() * 1000):0-999 整數int n = (int)(Math.random() * (max - min + 1)) + min:[min, max] 區間public class RandomTest {
public static void main(String[] args) {
double d = Math.random(); // 0.0-1.0
double d1000 = Math.random() * 1000; // 0.0-1000.0
int i1000 = (int)(Math.random() * 1000); // 0-999
System.out.println(d); System.out.println(d1000); System.out.println(i1000);
}
}
功能更豐富,支持多類型、種子控制:
import java.util.Random;
public class RandomTest {
public static void main(String[] args) {
Random random = new Random(); // 默認種子:System.nanoTime()
System.out.println("int: " + random.nextInt());
System.out.println("int[0,100): " + random.nextInt(100));
System.out.println("long: " + random.nextLong());
System.out.println("float: " + random.nextFloat()); // 0.0-1.0
System.out.println("double: " + random.nextDouble()); // 0.0-1.0
System.out.println("boolean: " + random.nextBoolean());
System.out.println("bytes: " + Arrays.toString(random.bytes(new byte[10])));
}
}
System.nanoTime() (高精度時間)new Random(100L),相同種子產生完全相同序列Random r1 = new Random(100);
Random r2 = new Random(100);
for (int i=0; i<5; i++) {
System.out.println(r1.nextInt() + "\t" + r2.nextInt()); // 輸出完全一致
}
import java.util.concurrent.ThreadLocalRandom;
// 無競爭、無共享狀態、性能優於 Random
int n = ThreadLocalRandom.current().nextInt(100);
long l = ThreadLocalRandom.current().nextLong(1000, 2000);
| 場景 | 推薦類 | 關鍵原因 |
|---|---|---|
| 簡單臨時隨機 | Math.random() | 無導包、一行代碼 |
| 多類型、區間、種子控制 | Random | 功能全、可重現 |
| 高並發、多線程環境 | ThreadLocalRandom | 無鎖、線程隔離、高性能 |
| 安全敏感 (密鑰、Token) | SecureRandom | 不可預測、加密強度 |