linux生成随机数 Random Math.random RandomStringUtils使用介绍

2016-05-27
admin
原创 1556
摘要:linux生成随机数 Random Math.random RandomStringUtils使用介绍

一、linux生成随机数

1、/dev/random:真随机源,没有足够的随机熵时会阻塞;
2、/dev/urandom:伪随机源,非阻塞,随机数不是真正的随机;

3、urandom读取:dd if=/dev/urandom bs=16 count=1 2>/dev/null | xxd -c16 -g16 -p

4、urandom速度:dd if=/dev/urandom of=/dev/null bs=512K,5MB/秒=125万INT/秒


random配置列表:

ls /proc/sys/kernel/random | cat
boot_id

uuid
poolsize

entropy_avail
read_wakeup_threshold
write_wakeup_threshold


random配置说明:

uuid,生成随机uuid;

poolsize,熵池大小,默认4096比特;

entropy_avail,可以使用的熵比特数量;

read_wakeup_threshold,多少熵唤醒等待读random设备的进程,默认64比特;

write_wakeup_threshold,多少熵唤醒等待写random设备的进程,默认64比特;


二、Random使用介绍

1、全名是java.util.Random

2、使用线性同余随机数发生器;

3、nextInt(int n)取值范围[0,n);

4、nextInt()取值范围2^32次方所有整数,包括正数、负数、

5、nextDouble()取值范围[0,1];


public static void testUtilRandom() {
long seed = System.nanoTime();
Random rand1 = new Random(seed);
Random rand2 = new Random(seed);
System.out.println(rand1.nextInt(100));
System.out.println(rand2.nextInt(100));
byte[] bytes = new byte[8];
rand1.nextBytes(bytes);
System.out.println(Arrays.toString(bytes));
rand2.nextBytes(bytes);
System.out.println(Arrays.toString(bytes));
}


输出:

70
70
[-25, -12, 30, -111, 123, 6, 11, 121]
[-25, -12, 30, -111, 123, 6, 11, 121]


三、Math.random使用介绍

1、Math.random内部持有java.util.Random静态实例;

2、Math.random内部调用Random.nextDouble,返回值位于[0,1]之间;


public static void testMathRandom() {
System.out.println(Math.random());
System.out.println(Math.random());
}


输出:

0.9758482010371091
0.3419060236681194


四、RandomStringUtils使用介绍

1、全名是org.apache.commons.lang.RandomStringUtils

2、RandomStringUtils包含一个Random实例,实际调用此实例

3、RandomStringUtils.randomNumeric,生成数字序列;

4、RandomStringUtils.randomAlphabetic,生成字母序列;

5、RandomStringUtils.randomAlphanumeric,生成字母数字序列;

6、RandomStringUtils.randomAscii,生成ascii码序列,范围是[32,127);

7、RandomStringUtils.random(count,chars),生成指定字符序列;

发表评论
评论通过审核之后才会显示。