Java基础教程——Random随机数类

Random类

java.util.Random类用于产生随机数。需要导入包:

import java.util.Random;
方法 解释
Random() 创建一个Random类对象
Random(long seed) 使用seed作为随机种子创建一个Random类对象
int nextInt() 下一个整型值
int nextInt(int bound) 0~bound-1之间的随机整数
long nextLong() 下一个长整型值
float nextFloat() 0.0到1.0之间的下一个浮点值
double nextDouble() 0.0到1.0之间的下一个双精度值

r.nextInt():产生整数范围的随机数(均匀分布)

import java.util.Random;
public class TestRadomNextInt {
	// int 值
	public static void main(String[] args) {
		Random r = new Random();
		for (int i = 1; i <= 10; i++) {
			int num = r.nextInt();
			System.out.println(num);
		}
	}
}

56845052
-686301646
-1233789074
1636415628
1894696653
-595067037
-1041962125
392105380
-226429564
116890454


nextInt(int bound):随机生成[0,bound)之间的整数。注意是左开右闭区间,可能取到0,不能取到bound的值。

bound:边界

import java.util.Random;
public class TestRadomNextInt {
	public static void main(String[] args) {
		Random r = new Random();
		for (int i = 1; i <= 10; i++) {
			int num = r.nextInt(10);
			System.out.println(num);
		}
	}
}

应用示例:生成10~20之间的随机数:
(1)范围:20-10=10,即随机数范围跨度为10,
r.nextInt(11)可以满足:[0——11)即[0——10]
(2)从10开始,则整体+10,即r.nextInt(11) + 10

import java.util.Random;
public class TestRandomRange {
	public static void main(String[] args) {
		Random r = new Random();
		for (int i = 0; i < 100; i++) {
			int n = r.nextInt(11) + 10;
			System.out.println(n);
		}
	}
}

归纳:生成a~b之间的随机数,只需要使用 r.nextInt(b-a+1)+a即可。


种子:Random(long seed)

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public class TestRadom {
	public static void main(String[] args) {
		无参随机数();
		无参随机数();
		带种子随机数();
		带种子随机数();
	}
	static void 无参随机数() {
		Random r = new Random();
		for (int i = 0; i < 10; i++) {
			System.out.print(r.nextInt(101) + "	");// 0-100的随机整数
		}
		System.out.println();
	}
	static void 带种子随机数() {
		Random r2 = new Random(100);
		for (int i = 0; i < 10; i++) {
			System.out.print(r2.nextInt(101) + " ");// 0-100的随机整数
		}
		System.out.println();
	}
}

运行结果:

59	41	10	41	4	80	7	69	32	91	
57	54	67	25	52	4	3	100	23	75	
92 94 52 24 1 74 60 55 56 4 
92 94 52 24 1 74 60 55 56 4 

↑通过运行结果可以发现,种子相同的情况下,生成的随机数其实是一样的——组内看似随机,但多次运行结果相同。
事实上,Random的无参构造方法中,使用了时间作为种子,源码如下:

    public Random() {
        this(seedUniquifier() ^ System.nanoTime());
    }

Java 7中,对Random类进行了升级,提供了ThreadLocalRandom类,在并发访问环境下,可以减少多线程的资源竞争,提升线程的安全性。

Random r = new Random();
↓
ThreadLocalRandom r = ThreadLocalRandom.current();
原文地址:https://www.cnblogs.com/tigerlion/p/11179190.html