1. 程式人生 > >java中隨機數Random和ThreadLocalRandom()用法與區別

java中隨機數Random和ThreadLocalRandom()用法與區別

package com.test;

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

public class M1001{
    public static void main(String[] args) {
        Random random = new Random();
        System.out.println("-----------產生1到10之間的隨機數----------------");
        System.out.println(random.nextInt
(10)); ThreadLocalRandom threadRandom = ThreadLocalRandom.current(); System.out.println(threadRandom.nextInt(10)); System.out.println("-----------產生兩個數之間的隨機數----------------"); System.out.println(threadRandom.nextInt(10,100)); } }

Random:生產一個偽隨機數(通過相同的種子,產生的隨機數是相同的)。

ThreadLocalRandom:是java7新增類,是Random的子類,在多執行緒併發情況下,THreadLocalRandom相對於Random可以減少多執行緒資源競爭,保證了執行緒的安全性。public class ThreadLocalRandom extends Random因為構造器是預設訪問許可權,只能在java.util包中建立物件,故提供了一個方法ThreadLocalRandom.current()用於返回當前類的物件.

UIID:通用唯一識別符號,在一臺機器上生成的數字,核心演算法網絡卡、當地時間和隨機數有關。
缺點:字串太長了。

package com.test;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

public class M1001{
    public static void main(String[] args) {
        Random random = new Random();
        System.out.println
("-----------產生1到10之間的隨機數----------------"); System.out.println(random.nextInt(10)); ThreadLocalRandom threadRandom = ThreadLocalRandom.current(); System.out.println(threadRandom.nextInt(10)); System.out.println("-------- ---產生兩個數之間的隨機數----------------"); System.out.println(threadRandom.nextInt(10,100)); System.out.println("---------------------------"); String uuid = UUID.randomUUID().toString(); System.out.println(uuid); } }

結果:20d86b2a-396d-4579-9717-a2cd0bdeed18