當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java ThreadLocalRandom ints()用法及代碼示例

Java ThreadLocalRandom 類的 ints() 方法返回一個有效的無限偽隨機 int 值流。此方法覆蓋 Random 類中的整數。

用法:

public IntStream ints()

參數:

NA

返回值:

此方法返回偽隨機 int 值流。

例子1

import java.util.concurrent.ThreadLocalRandom;

public class ThreadLocalRandomIntsExample1 {
    public static void main(String[] args) {
    	
    	// Returns a stream of pseudorandom int values   	
    	System.out.println("stream of pseudorandom int value is:" +ThreadLocalRandom.current().ints());
    }
}

輸出:

stream of pseudorandom int value is:[email protected]

Java ThreadLocalRandom ints(long streamSize) 方法

Java ThreadLocalRandom 類的 ints(long streamSize) 方法返回一個流,該流產生給定的 streamSize 數量的偽隨機 int 值。此方法覆蓋 Random 類中的整數。

用法:

public IntStream ints(long streamSize)

參數:

streamSize- 它是要生成的值的數量

返回值:

此方法返回一個 int 值流。

異常:

IllegalArgumentException:如果 streamSize 小於零,將拋出此異常。

例子1

import java.util.concurrent.ThreadLocalRandom;

public class ThreadLocalRandomIntsExample4 {
    public static void main(String[] args) {
    	
    	// Returns a stream of int values   	
    	System.out.println("stream of int value is:" +ThreadLocalRandom.current().ints(3899));
    }
}

輸出:

stream of int value is:[email protected]

例子2

import java.util.concurrent.ThreadLocalRandom;

public class ThreadLocalRandomIntsExample5 {
    public static void main(String[] args) {
    	
    	// Returns exception because streamSize is negative 
    	System.out.println("stream of int value is:" +ThreadLocalRandom.current().ints(-20));
    }
}

輸出:

Exception in thread "main" java.lang.IllegalArgumentException:size must be non-negative
	at java.base/java.util.concurrent.ThreadLocalRandom.ints(Unknown Source)
	at tests.ThreadLocalRandomIntsExample2.main(ThreadLocalRandomIntsExample2.java:7)

相關用法


注:本文由純淨天空篩選整理自 Java ThreadLocalRandom ints() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。