On several realization ways of random numbers in Java _java

Source: Internet
Author: User
Tags abs mathematical functions static class

As we all know, random numbers are one of the most basic features of any programming language. The basic way to generate random numbers is the same: generate a random number between 0 and 1. It seems simple, but sometimes we overlook some interesting features.

What do we learn from books?

The most obvious and intuitive way to generate random numbers in Java is simply to call:

Java.lang.Math.random ()

In all other languages, generating random numbers is like using the Math tool classes, such as ABS, POW, floor, sqrt, and other mathematical functions. Most people learn about this class through books, tutorials, and courses. A simple example: a double-precision floating-point number can be generated from 0.0 to 1.0. So through the information above, the developer is going to generate a double-precision floating-point number between 0.0 and 10.0 to write this:

Math.random () * 10

And an integer between 0 and 10 is written:

Math.Round (Math.random () * 10)

Advanced

By reading the source code of Math.random () or simply using the IDE's AutoComplete feature, developers can easily find that java.lang.Math.random () uses an internal randomly generated object-a very powerful object that can be flexibly randomly generated: Boolean, All numeric types, even Gaussian distributions. For example:

New Java.util.Random (). Nextint (10)

It has a drawback, is that it is an object. Its method must be invoked through an instance, which means that its constructor must be called first. An expression like the above is acceptable if there is sufficient memory, but it can cause problems when there is not enough memory.

A simple solution that avoids creating a new instance each time a random number needs to be generated, and that is using a static class. Guess you may have thought of Java.lang.Math, well, we are the initialization of improved java.lang.Math. Although the project is low, you need to do some simple unit tests to make sure it doesn't go wrong.

If the program needs to generate a random number to store, the problem comes again. For example, it is sometimes necessary to manipulate or protect seed (seed), an internal number to store the state and compute the next random number. In these special cases, it is not appropriate to share randomly generated objects.

Concurrent

In the context of Java EE multi-threaded applications, randomly generated instance objects can still be stored in classes or other implementation classes as a static property. Fortunately, Java.util.Random is thread-safe, so there is no risk that multiple thread invocations can damage seed (seed).

Another example of multithreading java.lang.ThreadLocal is the one that is worth considering. The lazy approach is to implement a single instance through the Java API itself, and of course you can ensure that each thread has its own instance object.

Although Java does not provide a good way to manage a single instance of Java.util.Random. However, the long-awaited Java 7 provides a new way to generate random numbers:

Java.util.concurrent.ThreadLocalRandom.current (). Nextint (10)

This new API combines the benefits of two other approaches: single instance/static access, just as flexible as math.random (). Threadlocalrandom is also faster than any other method that handles high concurrency.

Experience

Chris marasti-georg points out:

Math.Round (Math.random () * 10)

Make the distribution unbalanced, for example: 0.0-0.499999 will be rounded to 0, while 0.5 to 1.499999 will be rounded to 1. So how do you use legacy syntax to achieve the right equilibrium distribution, as follows:

Math.floor (Math.random () * 11)

Luckily, if we use Java.util.Random or java.util.concurrent.ThreadLocalRandom, we don't have to worry about the problem.

The Java Combat Project introduces some of the hazards of improper use of the Java.util.Random API. This lesson tells us not to use:

Math.Abs (Rnd.nextint ())%n

and use:

Rnd.nextint (N)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.