生成 `[min, max]` 區間整數 (包含兩端):
int randomInRange(int min, int max) {
if (min > max) { int t = min; min = max; max = t; } // 自動交換
return (int) (Math.random() * (max - min + 1)) + min;
}
import java.util.concurrent.ThreadLocalRandom;
int random = ThreadLocalRandom.current().nextInt(min, max + 1); // [min, max]
// 多線程環境下無競爭,性能優於 Math.random() (內部同步) 與 Random (共享種子)。
// Java 8+ Lambda 風格工具方法
public static int randomInt(int a, int b) {
return ThreadLocalRandom.current().nextInt(Math.min(a, b), Math.max(a, b) + 1);
}
拋棄 `Math.random()`,拥抱 `ThreadLocalRandom`,代碼更簡潔、性能更強、線程更安全。