Math&Random&ThreadLocalRandom类

mac2022-06-30  38

Math类

//绝对值值运算: Math.abs(18.999); //返回19.999这个数的绝对值 Math.abs(-12.58); // 返回-12.58这个数的绝对值,为12.58 //取值运算: Math.signum(x); //如果x大于0则返回1.0,小于0则返回-1.0,等于0则返回0 //取整运算: Math.ceil(-13.56); //返回最近的且大于这个数的整数, 为14.0 Math.floor(-13.56); //返回最近的且小于这个数的整数, 为13.0 Math.rint(13.56); 返回最接近这个数的整数,如果刚好居中,则取偶数,为14 //对数运算: Math.log10(100); // 以10为底数的100的对数 ,为2 //指数运算: Math.expm1(x); //e的x次幂 - Math.pow(a,b); //a的b次幂 Math.scalb(x, y); //x*(2的y次幂) //二次方根运算: Math.sqrt(x); //x的二次方根 //三次方根运算: Math.cbrt(x); //x的三次方根 //返回较大值和较小值: Math.max(x, y); //返回x、y中较大的数 Math.min(x, y); //返回x、y中较小的数 //三角函数运算: Math.sin(α); //sin(α)的值 Math.cos(α); //cos(α)的值 Math.tan(α); //tan(α)的值 //求角运算: Math.asin(x/z); //返回角度值[-π/2,π/2] arc sin(x/z) Math.acos(y/z); //返回角度值[0~π] arc cos(y/z) Math.atan(y/x); //返回角度值[-π/2,π/2] arctan(y/x) //随机值运算: Math.random(); //随机返回[0,1)之间的无符号double值

Random&ThreadLocalRandom类

Random类

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 }

ThreadLocalRandom类(推荐)

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://blog.csdn.net/qq_33213136/article/details/76242273https://www.imooc.com/article/29739

转载于:https://www.cnblogs.com/zongmin/p/11344169.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)