Random 是一个线程安全类,理论上可以通过它同时在多个线程中获得互不相同的随机数,但是在多线程的场景下需要多个线程竞争同一个原子变量的更新操作,性能不佳。
多线程性能参见:https://www.imooc.com/article/29739
有两种构造方法:
Random():以当前系统时间作为种子。Random(long seed):使用单个 long 型整数作为种子。 public static void main(String[] args) { Random rand = new Random(); //随机boolean值 System.out.println(rand.nextBoolean()); //true //随机填充byte数组 byte[] buffer = new byte[16]; rand.nextBytes(buffer); //[106, -85, 66, 108, 93, -22, 114, -67, -97, -99, 34, 126, 3, 66, -25, 59] System.out.println(Arrays.toString(buffer)); //随机[0.0, 1.0) 区间的double值 System.out.println(rand.nextDouble()); //0.6032052834419511 //随机[0.0, 1.0) 区间的float值 System.out.println(rand.nextFloat()); //0.19521767 //随机int范围的整数 System.out.println(rand.nextInt()); //-1557426129 //随机生成[0, 15)区间的整数 System.out.println(rand.nextInt(15)); //6 //随机long范围整数 System.out.println(rand.nextLong()); //868994934892445287 }ThreadLocalRandon 类是 JDK 1.7 新增的一个类,它是 Random 的增强版,在并发访问的环境下,使用它来代替 Random 可以减少多线程资源竞争,最终保证系统具有更好的线程安全性。ThreadLocalRandom 类提供了一个静态方法来获取当前线程的随机数生成器:
ThreadLocalRandom rand = ThreadLocalRandom.current();ThreadLocalRandom 方法的用法和 Random 基本类似,增加几个功能:
//返回一个boolean类型的随机数 public boolean nextBoolean(); //随机填充一个byte数组 public void nextBytes(byte[] bytes); //返回一个[0.0,1.0)范围的float随机数 public float nextFloat(); //返回一个[0.0,1.0)范围的double随机数 public double nextDouble(); //返回一个[0.0-bound)之间的double随机数 public double nextDouble(double bound); //返回一个[origin-bound)之间的随机数 public double nextDouble(double origin, double bound); //返回一个整型的伪随机数 public int nextInt(); //返回一个[0,bound)之间的随机数 public int nextInt(int bound); //返回一个[origin,bound)之间的随机数 public int nextInt(int origin, int bound); //返回一个long型随机数 public long nextLong(); //返回一个[0,bound)之间的随机数 public long nextLong(long bound); //返回一个[origin,bound)之间的随机数 public long nextLong(long origin, long bound);转载于:https://www.cnblogs.com/zongmin/p/11344169.html
相关资源:JAVA上百实例源码以及开源项目