📜  ThreadLocalRandom类

📅  最后修改于: 2020-11-15 03:52:19             🧑  作者: Mango


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

ThreadLocalRandom方法

以下是ThreadLocalRandom类中可用的重要方法的列表。

Sr.No. Method & Description
1

public static ThreadLocalRandom current()

Returns the current thread’s ThreadLocalRandom.

2

protected int next(int bits)

Generates the next pseudorandom number.

3

public double nextDouble(double n)

Returns a pseudorandom, uniformly distributed double value between 0 (inclusive) and the specified value (exclusive).

4

public double nextDouble(double least, double bound)

Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound (exclusive).

5

public int nextInt(int least, int bound)

Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound (exclusive).

6

public long nextLong(long n)

Returns a pseudorandom, uniformly distributed value between 0 (inclusive) and the specified value (exclusive).

7

public long nextLong(long least, long bound)

Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound (exclusive).

8

public void setSeed(long seed)

Throws 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类来获取随机数。