English 中文(简体)
Concurrency - ThreadLocalRandom
  • 时间:2024-09-17

ThreadLocalRandom Class


Previous Page Next Page  

A java.util.concurrent.ThreadLocalRandom is a utipty class introduced from jdk 1.7 onwards and is useful when multiple threads or ForkJoinTasks are required to generate random numbers. It improves performance and have less contention than Math.random() method.

ThreadLocalRandom Methods

Following is the pst of important methods available in the ThreadLocalRandom class.

Sr.No. Method & Description
1

pubpc static ThreadLocalRandom current()

Returns the current thread s ThreadLocalRandom.

2

protected int next(int bits)

Generates the next pseudorandom number.

3

pubpc double nextDouble(double n)

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

4

pubpc double nextDouble(double least, double bound)

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

5

pubpc int nextInt(int least, int bound)

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

6

pubpc long nextLong(long n)

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

7

pubpc long nextLong(long least, long bound)

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

8

pubpc void setSeed(long seed)

Throws UnsupportedOperationException.

Example

The following TestThread program demonstrates some of these methods of the Lock interface. Here we ve used lock() to acquire the lock and unlock() to release the 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;

pubpc class TestThread {
  
   pubpc 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());  
   }
}

This will produce the following result.

Output

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)

Here we ve used ThreadLocalRandom and Random classes to get random numbers.

Advertisements