【Java常用类库】_System类笔记

来源:互联网 发布:数字广播软件 编辑:程序博客网 时间:2024/05/21 20:35
【Java常用类库】_System类笔记

本章目标:
认识System类及一些常用方法
掌握垃圾对象的回收操作
了解对象的生命周期

3、具体内容
3.1、System类基本使用

System.out.println()本身就是一个系统提供好的类,而且out.println()方法也是经常使用到的。
System类是一些与系统相关的属性和方法的集合在System类中所有的属性都是静态的。

No.    方法定义                    类型        描述
1    public static void exit(int status)        普通        系统退出
2    public static void gc()                普通        垃圾回收
3    public staiic long currentTimeMillis()        普通        返回以毫秒为单位的当前时间
4    public static arraycopy(Object src,int        普通        数组拷贝
    srcPos,Object dest,int destPos,int length)
5    public static Properties getProperties()    普通        取得当前系统的全部属性
6    public static String getProperty(String key)    普通        根据键值取得属性的具体内容


一个对象如果不使用,则肯定要等待进行垃圾收集,垃圾收集可以自动调用也可以手工调用,手工调用System.gc()或者Runtime.getRuntime().gc()。但是,如果一个对象在回收之前需要做一些收尾工作,则就必须覆写Object类中的:
    protected void finalize() throws Throwable
在对象被回收之前进行调用,以处理对象回收之前的若干操作,例如释放资源。


实例一:
public class SystemDemo01{    public static void main(String args[]){        long startTime = System.currentTimeMillis() ;    // 取得开始计算之前的时间        int sum = 0 ;            // 声明变量        for(int i=0;i<30000000;i++){    // 执行累加操作            sum += i ;        }        long endTime = System.currentTimeMillis() ;    // 取得计算之后的时间        // 结束时间减去开始时间        System.out.println("计算所花费的时间:" + (endTime-startTime) +"毫秒") ;    }};



实例二:
public class SystemDemo02{    public static void main(String args[]){        System.getProperties().list(System.out) ;    // 列出系统的全部属性    }};



实例三:
public class SystemDemo03{    public static void main(String args[]){        System.out.println("系统版本:" + System.getProperty("os.name")            + System.getProperty("os.version")            + System.getProperty("os.arch")) ;        System.out.println("系统用户:" + System.getProperty("user.name")) ;        System.out.println("当前用户目录:" + System.getProperty("user.home")) ;        System.out.println("当前用户工作目录:" + System.getProperty("user.dir")) ;    }};



实例四:
class Person{    private String name ;    private int age ;    public Person(String name,int age){        this.name = name ;        this.age = age;    }    public String toString(){    // 覆写toString()方法        return "姓名:" + this.name + ",年龄:" + this.age ;    }    public void finalize() throws Throwable{    // 对象释放空间时默认调用此方法        System.out.println("对象被释放 --> " + this) ;    }};


public class SystemDemo04{    public static void main(String args[]){        Person per = new Person("张三",30) ;        per = null ;    // 断开引用        System.gc() ;        // 强制性释放空间    }};


原创粉丝点击