当前位置: 首页 > 图灵资讯 > 技术篇> Runtime - 运行时环境类(JVM)和大数值运算(BigInteger、BigDecimal)

Runtime - 运行时环境类(JVM)和大数值运算(BigInteger、BigDecimal)

来源:图灵教育
时间:2023-06-12 09:24:47

Runtime代表Java程序的运行环境 getRuntime 获取当前操作时的方法。

应用程序不能自己创建Runtime对象,可以通过Runtime的静态方法获得Runtime()。

Runtime类可访问jvm的相关信息

1、处理器数量

runtime.availableProcessors()

2、内存信息

“获得最大内存数” --》 runtime.maxMemory()

“获取闲置内存数” --》runtime.freeMemory()

Runtime应用

此外,一个程序的速度也可以通过Runtime来判断,从而看其运行程序的效率:时长+内存。

1.直接用str字符串拼接

Runtime runtime = Runtime.getRuntime();///获得Rantime的对象long startMemory = runtime.freeMemory();////获取开始的内存数量long startTime = System.currentTimeMillis();String str = "你好,小伙子";for (int i = 0; i < 10000; i++) {str += "你好,小伙子";}System.out.println(“字符串长度:” + str.length());long endTime = System.currentTimeMillis();long endMemory = runtime.freeMemory();///获得最终内存数量System.out.println("消耗时长:" + (endTime-startTime));//175毫秒Systems.out.println("消耗内存:" + (startMemory-endMemory));///-167506344//(内存消耗为负,由于new对象的持续存储,当内存不足时,垃圾回收器(JC)干预,回收一些闲置内存)

2.用Stringbuilder拼接

Runtime runtime = Runtime.getRuntime();long startMemory = runtime.freeMemory();long startTime = System.currentTimeMillis();StringBuilder sb = new StringBuilder(60006);sb.append("你好,小伙子");for (int i = 0; i < 10000; i++) {sb.append("你好,小伙子");}System.out.println(“字符串长度:” + sb.length());long endTime = System.currentTimeMillis();long endMemory = runtime.freeMemory();System.out.println("消耗时长:" + (endTime-startTime));//1毫秒Systemstem.out.println("消耗内存:" + (startMemory-endMemory));//0

大数值运算

出现原因:

int i1 = 1234567890;int i2 = 1234567890;System.out.println(i1 + i2);//-1825831516-由于数字过大,加上Int类型的值范围,精度丧失

1.整数大数值运算类 BigInteger

//参数传输到StringBigInterer big1 = new BigInteger("1234567891234567890");//继承NumberbigInter big2 = new BigInteger("1234567891234567890");BigInteger add = big1.add(big2);////加法Systememem加法.out.println(add);BigInteger subtract = big1.subtract(big2);System.out.println(subtract);////减法BigIntegerer multiply = big1.multiply(big2);System.out.println(multiply);///乘法BigInteger pide = big1.pide(big2);System.out.println(pide);//除法

注:整数和小数值运算引入的参数都是String类型

2.小数大数值运算类 BigDecimal

System.out.println(0.5 - 0.4);//0.09999999999999998  //将失去精度//参数传输到String类型BigDecimallimal big1 = new BigDecimal("0.5");///继承NumberbigDecimal big2 = new BigDecimal("0.4");BigDecimal add = big1.add(big2);////加法Systememem加法.out.println(add);BigDecimal subtract = big1.subtract(big2);System.out.println(subtract);////减法BigDecimal multiply = big1.multiply(big2);System.out.println(multiply);///乘法BigDecimal pide = big1.pide(big2);System.out.println(pide);//除法

特殊情况

BigDecimal big1 = new BigDecimal("10");BigDecimal big2 = new BigDecimal("3");//BigDecimal pide1 = big1.pide(big2);//System.out.println(pide1);//BigDecimal会报算异常 pide = big1.pide(big2, 3, BigDecimal.ROUND_HALF_UP);//四舍五入三小数System.out.println(pide);//3.333