
- Java 併發教程
- 併發 - 首頁
- 併發 - 概述
- 併發 - 環境設定
- 併發 - 主要操作
- 執行緒間通訊
- 併發 - 同步
- 併發 - 死鎖
- 工具類示例
- 併發 - ThreadLocal
- 併發 - ThreadLocalRandom
- 鎖示例
- 併發 - 鎖
- 併發 - 讀寫鎖
- 併發 - 條件
- 原子變數示例
- 併發 - AtomicInteger
- 併發 - AtomicLong
- 併發 - AtomicBoolean
- 併發 - AtomicReference
- 併發 - AtomicIntegerArray
- 併發 - AtomicLongArray
- 併發 - AtomicReferenceArray
- 執行器示例
- 併發 - 執行器
- 併發 - ExecutorService
- ScheduledExecutorService
- 執行緒池示例
- 併發 - newFixedThreadPool
- 併發 - newCachedThreadPool
- newScheduledThreadPool
- newSingleThreadExecutor
- 併發 - ThreadPoolExecutor
- ScheduledThreadPoolExecutor
- 高階示例
- 併發 - Futures 和 Callables
- 併發 - Fork-Join 框架
- 併發集合
- 併發 - BlockingQueue
- 併發 - ConcurrentMap
- ConcurrentNavigableMap
- 併發有用資源
- 併發 - 快速指南
- 併發 - 有用資源
- 併發 - 討論
ThreadLocalRandom 類
java.util.concurrent.ThreadLocalRandom 是從 jdk 1.7 開始引入的工具類,當多個執行緒或 ForkJoinTasks 需要生成隨機數時非常有用。它比 Math.random() 方法效能更好,競爭更少。
ThreadLocalRandom 方法
以下是 ThreadLocalRandom 類中一些重要方法的列表。
序號 | 方法及描述 |
---|---|
1 | public static ThreadLocalRandom current() 返回當前執行緒的 ThreadLocalRandom。 |
2 | protected int next(int bits) 生成下一個偽隨機數。 |
3 | public double nextDouble(double n) 返回一個偽隨機的、均勻分佈的 double 值,介於 0(包含)和指定值(不包含)之間。 |
4 | public double nextDouble(double least, double bound) 返回一個偽隨機的、均勻分佈的值,介於給定的最小值(包含)和邊界值(不包含)之間。 |
5 | public int nextInt(int least, int bound) 返回一個偽隨機的、均勻分佈的值,介於給定的最小值(包含)和邊界值(不包含)之間。 |
6 | public long nextLong(long n) 返回一個偽隨機的、均勻分佈的值,介於 0(包含)和指定值(不包含)之間。 |
7 | public long nextLong(long least, long bound) 返回一個偽隨機的、均勻分佈的值,介於給定的最小值(包含)和邊界值(不包含)之間。 |
8 | public void setSeed(long seed) 丟擲 UnsupportedOperationException。 |
示例
下面的 TestThread 程式演示了 Lock 介面的一些方法。在這裡,我們使用了 lock() 來獲取鎖,使用 unlock() 來釋放鎖。
import java.util.Random; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.ThreadLocalRandom; public class TestThread { public static void main(final String[] arguments) { System.out.println("Random Integer: " + new Random().nextInt()); System.out.println("Seeded Random Integer: " + new Random(15).nextInt()); System.out.println( "Thread Local Random Integer: " + ThreadLocalRandom.current().nextInt()); final ThreadLocalRandom random = ThreadLocalRandom.current(); random.setSeed(15); //exception will come as seeding is not allowed in ThreadLocalRandom. System.out.println("Seeded Thread Local Random Integer: " + random.nextInt()); } }
這將產生以下結果。
輸出
Random Integer: 1566889198 Seeded Random Integer: -1159716814 Thread Local Random Integer: 358693993 Exception in thread "main" java.lang.UnsupportedOperationException at java.util.concurrent.ThreadLocalRandom.setSeed(Unknown Source) at TestThread.main(TestThread.java:21)
在這裡,我們使用了 ThreadLocalRandom 和 Random 類來獲取隨機數。