5 ways to generate random numbers in Java, how many do you know?

5 ways to generate random numbers in Java, how many do you know?

1. Math.random() static method

The random number generated is one between 0-1 double, ie 0 <= random <= 1.

use:

for (int i = 0; i < 10; i++) {
  System.out.println(Math.random());}

result:

0.3598613895606426 0.2666778145365811 0.25090731064243355 0.011064998061666276 0.600686228175639 0.9084006027629496 0.12700524654847833 0.6084605849069343 0.7290804782514261 0.9923831908303121

Implementation principle:

When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression new java.util.Random() This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else.

When the first call Math.random()when the method automatically creates a pseudo-random number generator , is actually in the new java.util.Random(). When the next call to continue Math.random()when the method will use the new pseudo-random number generator .

The source code is as follows:

public static double random() {
    Random rnd = randomNumberGenerator;
    if (rnd == null) rnd = initRNG(); // first call, create a pseudo-random number generator
    return rnd.nextDouble();}private static synchronized Random initRNG() {
    Random rnd = randomNumberGenerator;
    return (rnd == null)? (randomNumberGenerator = new Random()): rnd; // Actually use new java.util.Random())
This method is properly synchronized to allow correct use by more than one thread. However, if many threads need to generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom-number generator.

initRNG()The method is synchronized, so in a multithreaded case, only one thread is responsible for creating a pseudo-random number generator (using the current time as a seed), other threads are using this pseudo-random number generator generates a random number.

Therefore the method is thread safe.Math.random()

When the random number generation thread is not safe:

  • Thread 1 first call random()to create a generator when generator1using the current time as the seed.
  • Thread 2 at the first call random()to create a generator when generator2using the current time as the seed.
  • Happen generator1 and generator2use the same seed, resulting in generator1the random number generated each time and after generator2a random number generated after the same.

Under what circumstances is the generation of random numbers thread-safe: Math.random() static method use

  • Thread 1 first call random()to create a generator when generator1using the current time as the seed.
  • Thread 2 at the first call random()found that has a generator generator1, the generator directly generator1.
public class JavaRandom {
    public static void main(String args[]) {
        new MyThread().start();
        new MyThread().start();
    }}class MyThread extends Thread {
    public void run() {
        for (int i = 0; i < 2; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + Math.random());
        }
    }}

result:

Thread-1: 0.8043581595645333 Thread-0: 0.9338269554390357 Thread-1: 0.5571569413128877 Thread-0: 0.37484586843392464

2. java.util.Random tool class

Basic algorithm: linear congruential pseudorandom number generator (LGC) linear congruential pseudorandom number generator Disadvantages: predictable

An attacker will simply compute the seed from the output values ​​observed. This takes significantly less time than 2^48 in the case of java.util.Random. The seed value can be easily calculated from the output. It is shown that you can predict future Random outputs observing only two(!) output values ​​in time roughly 2^16. Therefore, you can predict the random number of the next output. You should never use an LCG for security-critical purposes. In applications that focus on information security, do not use the LCG algorithm to generate random numbers, please use SecureRandom.

use:

Random random = new Random();for (int i = 0; i < 5; i++) {
    System.out.println(random.nextInt());}

result:

-24520987 -96094681 -952622427 300260419 1489256498

The Random class uses the current system clock as the seed by default:

public Random() {
    this(seedUniquifier() ^ System.nanoTime());}public Random(long seed) {
    if (getClass() == Random.class)
        this.seed = new AtomicLong(initialScramble(seed));
    else {
        // subclass might have overriden setSeed
        this.seed = new AtomicLong();
        setSeed(seed);
    }}

Methods provided by the Random class: API

  • nextBoolean()- Returns uniform distribution trueorfalse
  • nextBytes(byte[] bytes)
  • nextDouble() -Returns uniformly distributed between 0.0 and 1.0 double
  • nextFloat() -Returns uniformly distributed between 0.0 and 1.0 float
  • nextGaussian()-Returns the Gaussian distribution (ie normal distribution) between 0.0 and 1.0 double
  • nextInt() -Return evenly distributed int
  • nextInt(int n)-Return uniformly distributed between 0 and n int(including 0, excluding n)
  • nextLong() -Return evenly distributed long
  • setSeed(long seed) -Set seed

As long as the seed is the same, the random number generated is the same: because the seed is determined, the random number algorithm is also determined, so the output is determined!

Random random1 = new Random(10000);Random random2 = new Random(10000);for (int i = 0; i < 5; i++) {
    System.out.println(random1.nextInt() + " = " + random2.nextInt());}

result:

-498702880 = -498702880 -858606152 = -858606152 1942818232 = 1942818232 -1044940345 = -1044940345 1588429001 = 1588429001

3. java.util.concurrent.ThreadLocalRandom tool class

ThreadLocalRandomIt is provided after JDK 7 and also inherited from java.util.Random.

private static final ThreadLocal<ThreadLocalRandom> localRandom =
    new ThreadLocal<ThreadLocalRandom>() {
        protected ThreadLocalRandom initialValue() {
            return new ThreadLocalRandom();
        }};

Each thread has an independent random number generator, which is used to generate random numbers concurrently, which can solve the contention and contention of multiple threads. higher efficiency! Follow the official account Java technology stack and reply to java for more Java tool tutorials.

ThreadLocalRandomNot directly newinstantiated, but the use of the first static method current()to give ThreadLocal<ThreadLocalRandom>examples, and then call java.util.Randoma method of the class provides access to a variety of random numbers.

use:

public class JavaRandom {
    public static void main(String args[]) {
        new MyThread().start();
        new MyThread().start();
    }}class MyThread extends Thread {
    public void run() {
        for (int i = 0; i < 2; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + ThreadLocalRandom.current().nextDouble());
        }
    }}

result:

Thread-0: 0.13267085355389086 Thread-1: 0.1138484950410098 Thread-0: 0.17187774671469858 Thread-1: 0.9305225910262372

4. java.Security.SecureRandom

It is also inherited from java.util.Random.

Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications. SecureRandom takes Random Data from your os (they can be interval between keystrokes etc- most os collect these data store them in files-/dev/random and /dev/urandom in case of linux/solaris) and uses that as the seed. The operating system collects some random events, such as mouse clicks, keyboard clicks, etc., SecureRandom uses these random events as seeds.

SecureRandomProvide an encrypted strong random number generator (RNG), which requires that the seed must be unpredictable and produce non-deterministic output. SecureRandomAlso it provides implementation-independent algorithms, whereby a caller (application code) requests a particular RNG algorithm and is handed back to the algorithm SecureRandomobject.

  • If only the algorithm name is specified, as shown below:SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
  • If both the algorithm name and the package provider are specified, as shown below:SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");

use:

SecureRandom random1 = SecureRandom.getInstance("SHA1PRNG");SecureRandom random2 = SecureRandom.getInstance("SHA1PRNG");for (int i = 0; i < 5; i++) {
    System.out.println(random1.nextInt() + " != " + random2.nextInt());}

result:

704046703 != 2117229935 60819811 != 107252259 425075610 != -295395347 682299589 != -1637998900 -1147654329 != 1418666937

5. Random string

Apache Commons-Lang package can be used RandomStringUtilsbased. Maven depends on the following:

<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version></dependency>

API reference: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/RandomStringUtils.html

Example:

public class RandomStringDemo {
    public static void main(String[] args) {
        // Creates a 64 chars length random string of number.
        String result = RandomStringUtils.random(64, false, true);
        System.out.println("random = " + result);

        // Creates a 64 chars length of random alphabetic string.
        result = RandomStringUtils.randomAlphabetic(64);
        System.out.println("random = " + result);

        // Creates a 32 chars length of random ascii string.
        result = RandomStringUtils.randomAscii(32);
        System.out.println("random = " + result);

        // Creates a 32 chars length of string from the defined array of
        // characters including numeric and alphabetic characters.
        result = RandomStringUtils.random(32, 0, 20, true, true, "qw32rfHIJk9iQ8Ud7h0X".toCharArray());
        System.out.println("random = " + result);

    }}

RandomStringUtilsOn the implementation class is also dependent on the java.util.Randomtools:

5272be2e3af36f9e2ca672e69a913c3d.jpg

Definition of RandomStringUtils class

reference:


Author: full-time walk-on
description link: the Java random numbers Random VS SecureRandom
original source: Jane books
invasion deleted

39f85e8a3d52019b640ce9ba4c1b1f94.jpeg

Guess you like

Origin blog.51cto.com/15050718/2621820