开发手册 欢迎您!
软件开发者资料库

ThreadLocalRandom类

Java Concurrency ThreadLocalRandom - 从简单和简单的步骤学习Java并发,从基本到高级概念,包括概述,环境设置,主要操作,线程通信,同步,死锁,ThreadLocal,ThreadLocalRandom,Lock,ReadWriteLock,Condition,AtomicInteger,AtomicLong, AtomicBoolean,AtomicReference,AtomicIntegerArray,AtomicLongArray,AtomicReferenceArray,Executor,ExecutorService,ScheduledExecutorService,newFixedThreadPool,newCachedThreadPool,newScheduledThreadPool,newSingleThreadExecutor,ThreadPoolExecutor,ScheduledThreadPoolExecutor,Futures and Callables,Fork-Join框架,BlockingQueue,ConcurrentMap,ConcurrentNavigableMap。

java.util.concurrent.ThreadLocalRandom是从jdk 1.7开始引入的实用程序类,当需要多个线程或ForkJoinTasks生成随机数时非常有用.它比Math.random()方法提高了性能并减少了争用.

ThreadLocalRandom方法

以下是ThreadLocalRandom中可用的重要方法列表class.

Sr.No.方法&说明
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)

Ret urns伪随机,在给定的最小值(包括)和bound(不包括)之间均匀分布的值.

6

public long nextLong(long n)

返回0(包括)和指定值(不包括)之间的伪随机均匀分布值.

7

public long nextLong(long least, long bound)

返回给定最小值(包括)和bound(不包括)之间的伪随机均匀分布值.

8

public void setSeed(long seed)

抛出UnsupportedOperationException.

示例

以下TestThread程序演示了Lock接口的一些方法.这里我们使用lock()来获取锁定和解锁()以释放锁定.

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: 1566889198Seeded Random Integer: -1159716814Thread Local Random Integer: 358693993Exception in thread "main" java.lang.UnsupportedOperationException        at java.util.concurrent.ThreadLocalRandom.setSeed(Unknown Source)        at TestThread.main(TestThread.java:21)

这里我们使用ThreadLocalRandom和Random类来获取随机数.