Java basics of random numbers

A random number
①.Random class
Random class for the production of a pseudo random number (the same seed by the random number generation is the same).
public Random (): Use the default seed (the current system time as seed).
public Random (long seed): according to the specified seed.

public class RandomDemo {
    public static void main(String[] args) {
        Random random =new Random();
        int num = random.nextInt(100);
        System.out.println(num);
    }
}

②ThreadLocalRandom class
ThreadLocalRandom is Java7 new class is a subclass of Random class, in the case of multi-threaded, ThreadLocalRandom relative Random multithreading can reduce competition for resources, to ensure the safety of the thread.
Because the configuration is the default access only to create objects in the java.util package, therefore, it provides a method ThreadLocalRandom.current () Returns the current class object.

public class ThreadLocalRandomDemo {
    public static void main(String[] args) {
        ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
        //可直接生成指定范围内的随机数
        int num = threadLocalRandom.nextInt(10, 100);
        System.out.println(num);
    }
}

③UUID class
universally unique identification: Universally Unique Identifier; produced on a machine number, ensure that all machines in the same space and time are unique.
UUID is a 128-bit long number, typically hexadecimal notation. The core idea is to combine machine card, local time, a number immediately to generate the UUID.
We generally used to indicate: a unique string random.

public class UUIDDemo {
    public static void main(String[] args) {
        String uuid = UUID.randomUUID().toString();
        System.out.println(uuid);
    }
}

Generating a verification code
① codes generated by the numbers and letters of

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class RandomTest {
    public static void main(String[] args) {
        String[] beforeShuffle = new String[]{"0","1","2", "3", "4", "5", "6", "7",
                "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
                "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "X", "Y", "Z"};
        List list = Arrays.asList(beforeShuffle);
        Collections.shuffle(list);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i));
        }
        String afterShuffle = sb.toString();
        System.out.println(afterShuffle);
        String result = afterShuffle.substring(5, 11);
        System.out.print(result);
    }
}

② generating digital codes consisting of only

 System.out.println((int)((Math.random()*9+1)*100000));
Published 99 original articles · won praise 2 · Views 2624

Guess you like

Origin blog.csdn.net/weixin_41588751/article/details/105127837