Java中java.util.Random的用法

java.util.Random是Java中用于生成伪随机数的类,提供了多种生成不同类型随机数的方法。

基本用法

1. 创建Random对象

import java.util.Random;

// 创建Random对象(使用默认种子,通常是系统时间)
Random random = new Random();

// 创建Random对象(使用指定种子)
Random randomWithSeed = new Random(12345L);

2. 生成不同类型的随机数

Random random = new Random();

// 生成整数
int randomInt = random.nextInt();           // 任意整数
int randomIntInRange = random.nextInt(100); // 0-99之间的整数

// 生成长整数
long randomLong = random.nextLong();

// 生成浮点数
float randomFloat = random.nextFloat();     // 0.0-1.0之间的浮点数
double randomDouble = random.nextDouble();  // 0.0-1.0之间的双精度浮点数

// 生成布尔值
boolean randomBoolean = random.nextBoolean();

// 生成字节数组
byte[] bytes = new byte[10];
random.nextBytes(bytes);  // 用随机字节填充数组

实际应用示例

1. 生成指定范围的随机数

Random random = new Random();

// 生成1-100之间的随机整数
int num1To100 = random.nextInt(100) + 1;

// 生成50-100之间的随机整数
int num50To100 = random.nextInt(51) + 50;

// 生成-10到10之间的随机整数
int numNegativeToPositive = random.nextInt(21) - 10;

2. 模拟掷骰子

public class DiceRoller {
    public static void main(String[] args) {
        Random random = new Random();
        
        // 模拟掷一个六面骰子
        int diceRoll = random.nextInt(6) + 1;
        System.out.println("骰子点数: " + diceRoll);
        
        // 模拟掷两个骰子
        int dice1 = random.nextInt(6) + 1;
        int dice2 = random.nextInt(6) + 1;
        int total = dice1 + dice2;
        System.out.println("骰子1: " + dice1 + ", 骰子2: " + dice2 + ", 总和: " + total);
    }
}

3. 随机选择数组元素

public class RandomArrayElement {
    public static void main(String[] args) {
        String[] fruits = {"苹果", "香蕉", "橙子", "葡萄", "草莓"};
        Random random = new Random();
        
        // 随机选择一个水果
        int randomIndex = random.nextInt(fruits.length);
        String randomFruit = fruits[randomIndex];
        System.out.println("随机选择的水果: " + randomFruit);
        
        // 随机打乱数组顺序
        for (int i = fruits.length - 1; i > 0; i--) {
            int j = random.nextInt(i + 1);
            // 交换元素
            String temp = fruits[i];
            fruits[i] = fruits[j];
            fruits[j] = temp;
        }
        System.out.println("打乱后的数组: " + Arrays.toString(fruits));
    }
}

4. 生成随机密码

public class PasswordGenerator {
    private static final String CHARACTERS = 
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%";
    
    public static String generatePassword(int length) {
        Random random = new Random();
        StringBuilder password = new StringBuilder();
        
        for (int i = 0; i < length; i++) {
            int randomIndex = random.nextInt(CHARACTERS.length());
            password.append(CHARACTERS.charAt(randomIndex));
        }
        
        return password.toString();
    }
    
    public static void main(String[] args) {
        String password = generatePassword(12);
        System.out.println("生成的密码: " + password);
    }
}

种子(Seed)的重要性

public class SeedExample {
    public static void main(String[] args) {
        // 使用相同种子的Random对象会生成相同的随机数序列
        Random random1 = new Random(12345L);
        Random random2 = new Random(12345L);
        
        System.out.println("相同种子的随机数序列:");
        for (int i = 0; i < 5; i++) {
            System.out.println("random1: " + random1.nextInt(100) + 
                             ", random2: " + random2.nextInt(100));
        }
        
        // 使用不同种子的Random对象会生成不同的随机数序列
        Random random3 = new Random();
        Random random4 = new Random();
        
        System.out.println("\n不同种子的随机数序列:");
        for (int i = 0; i < 5; i++) {
            System.out.println("random3: " + random3.nextInt(100) + 
                             ", random4: " + random4.nextInt(100));
        }
    }
}

线程安全版本

对于多线程环境,可以使用ThreadLocalRandom

import java.util.concurrent.ThreadLocalRandom;

public class ThreadLocalRandomExample {
    public static void main(String[] args) {
        // 在单个线程中使用
        int randomNum = ThreadLocalRandom.current().nextInt(1, 101); // 1-100
        
        // 在多线程环境中使用
        Runnable task = () -> {
            int threadRandom = ThreadLocalRandom.current().nextInt(1000);
            System.out.println(Thread.currentThread().getName() + ": " + threadRandom);
        };
        
        // 启动多个线程
        for (int i = 0; i < 5; i++) {
            new Thread(task).start();
        }
    }
}

注意事项

  1. 性能考虑: 创建Random对象相对昂贵,避免在循环中重复创建
  2. 种子安全性: 不要使用容易被猜测的种子
  3. 加密安全: 对于加密应用,使用java.security.SecureRandom
  4. 线程安全: Random是线程安全的,但ThreadLocalRandom在多线程环境中性能更好

这些示例展示了java.util.Random的基本用法和常见应用场景,你可以根据具体需求进行调整和扩展。

posted @ 2025-10-19 16:52  吹吹风喝喝酒  阅读(5)  评论(0)    收藏  举报