System类和Rubtime类
一、System类
1、getProperties()方法
这个方法可以获得系统的全部属性,包括虚拟机版本号,用户的国家,操作系统的版本等等。
import java.util.Properties;
import java.util.Set;
public class Example005 {
public static void main(String[] args) {
Properties p = new Properties();
System.out.println(p);
Set<String>propertyNames = p.stringPropertyNames();
for(String key:propertyNames){
String value =System.getProperty(key);
System.out.println(key+"--->"+value);
}
}
}
2、currentTimeMiles()方法
本方法就是反应的当前时间和1970年1月1日的时间差,单位为毫秒。也被称为时间戳。
public class Example006 {
public static void main(String[] args) {
long startime = System.currentTimeMillis();
int sum = 0;
for(int i=0;i<10000000;i++){
sum += i;
}
long endtime = System.currentTimeMillis();
System.out.println("运行时间为"+(endtime-startime)+"毫秒");
System.out.println(endtime);
}
}
这样的方式可以计算程序运行的实际时间。
3、arraycopy(源数组,拷贝起始位置,目标数组,要拷贝的位置,拷贝的个数)方法
本方法就是将一个数组的数据拷贝到另一个数组上。
public class Example006 {
public static void main(String[] args) {
int[] src ={1,2,3,4,5};
int[] dest = {11,22,3,44,55};
System.arraycopy(src,2,dest,0,3);
for(int i=0;i<dest.length;i++){
System.out.println(dest[i]);
}
}
}
要注意的是,两个数组的数据类型必须是一致的。而且拷贝的大小不能超过两个数组所能承受的范围。
System类中的常用方法还有gc()和exit(),前者用来启动垃圾回收处理,后者对系统进行终止。
二、Runtime类
本类用于表示JVM的运行状态,每次对JVM的使用都会创立一个对应的Runtime实例。
public class Example006 {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
System.out.println("处理器的个数"+rt.availableProcessors()+"个");
System.out.println("空闲内存的大小"+rt.freeMemory()/1024/1024+"M");
System.out.println("最大可用内存大小"+rt.maxMemory()/1024/1024+"M");
}
}
public class Example006 {
public static void main(String[] args) throws Exception
{
Runtime rt = Runtime.getRuntime();
Process process = rt.exec("notepad.exe");
Thread.sleep(3000);
process.destroy();
}
}
exec()的方法类似于DOS命令,可以直接调用一些文件。上面这段代码就是打开记事本然后在三面之后再关闭。
三、Math类
本类就是一个纯数学的工具类,它的构造方法是由private来修饰,所以无法创造对象。而且Mathle类的方法都是静态方法,所以我们直接使用类名来使用,其中的PI和E作为静态常量分别表示π和e。
public class Example006 {
public static void main(String[] args)
{
System.out.println("计算绝对值的结果"+Math.abs(-7));
System.out.println("计算正弦的结果"+Math.sin(1.57));
System.out.println("计算平方根的结果"+Math.sqrt(4));
System.out.println("计算立方根的结果"+Math.cbrt(9));
System.out.println("计算乘方的结果"+Math.pow(2,2));
System.out.println("求大于参数的最小整数"+Math.ceil(4.6));
System.out.println("求小于参数的最小整数"+Math.floor(-5.2));
System.out.println("对小数四舍五入的结果"+Math.round(-8.4));
System.out.println("比较最大值"+Math.max(25,45));
System.out.println("生成一个随机大于等于0.0且小于1.0的数"+Math.random());
}
}
四、Random类
import java.util.Random;
public class Example006 {
public static void main(String[] args)
{
Random r = new Random();
System.out.println("生成Boolbean类型的随机数"+r.nextBoolean());
System.out.println("生成double类型的随机数"+r.nextDouble());
System.out.println("生成float类型的随机数"+r.nextFloat());
System.out.println("生成int类型的随机数"+r.nextInt());
System.out.println("生成类0-10的随机数"+r.nextInt(10));
System.out.println("生成long类型的随机数"+r.nextLong());
}
}