Runtime代表Java程序的运行时环境,可以通过 getRuntime 方法获取当前运行时。
应用程序不能自己创建Runtime对象,可以通过Runtime的静态方法getRuntime()获得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毫秒
System.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毫秒
System.out.println("消耗内存:" + (startMemory-endMemory));//0
大数值运算
出现原因:
int i1 = 1234567890;
int i2 = 1234567890;
System.out.println(i1 + i2);//-1825831516--因为数字过大相加过后超过Int类型的取值范围,失去精度
1.整数大数值运算类 BigInteger
//参数传入String类型
BigInteger big1 = new BigInteger("1234567891234567890");//继承的Number
BigInteger big2 = new BigInteger("1234567891234567890");
BigInteger add = big1.add(big2);//加法
System.out.println(add);
BigInteger subtract = big1.subtract(big2);
System.out.println(subtract);//减法
BigInteger multiply = big1.multiply(big2);
System.out.println(multiply);//乘法
BigInteger divide = big1.divide(big2);
System.out.println(divide);//除法
注意:无论是整数还是小数的大数值运算传入的参数都是String类型
2.小数大数值运算类 BigDecimal
System.out.println(0.5 - 0.4);//0.09999999999999998 //会失去精度
//参数传入String类型
BigDecimal big1 = new BigDecimal("0.5");//继承的Number
BigDecimal big2 = new BigDecimal("0.4");
BigDecimal add = big1.add(big2);//加法
System.out.println(add);
BigDecimal subtract = big1.subtract(big2);
System.out.println(subtract);//减法
BigDecimal multiply = big1.multiply(big2);
System.out.println(multiply);//乘法
BigDecimal divide = big1.divide(big2);
System.out.println(divide);//除法
特殊情况
BigDecimal big1 = new BigDecimal("10");
BigDecimal big2 = new BigDecimal("3");
//BigDecimal divide1 = big1.divide(big2);
//System.out.println(divide1);//会报算数异常
BigDecimal divide = big1.divide(big2, 3, BigDecimal.ROUND_HALF_UP);//四舍五入三位小数
System.out.println(divide);//3.333
标签:BigInteger,BigDecimal,big2,big1,System,JVM,println,Runtime,out
From: https://blog.51cto.com/u_16154651/6458206