Java基础案例教程 第五章JavaAPI——-5.2System类和RunTime类的使用

一、System类

 

1、System类概述

      System 类包含一些有用的类字段和方法。它不能被实例化。

2、成员方法

System 中的方法全部用 static 修饰,可以用类名称直接调用,例如 System.getProperties();

1)public static Properties getProperties(){}      

     System.getProperties().list(System.out);  -->确定当前系统属性。

2)public static String getProperties(String key){}    

     System.getProperty(String key);  --> 获取当前键指定的系统属性。

3)public static void gc():运行垃圾回收器

      System.gc()可用于垃圾回收。当使用System.gc()回收某个对象所占用的内存之前,通过要求程序调用适当的方法来清理资源。在没有明确指定资源清理的情况下,Java提高了默认机制来清理该对象的资源,就是调用Object类的finalize()方法。finalize()方法的作用是释放一个对象占用的内存空间时,会被JVM调用。而子类重写该方法,就可以清理对象占用的资源,该方法有没有链式调用,所以必须手动实现。        

       从程序的运行结果可以发现,执行System.gc()前,系统会自动调用finalize()方法清除对象占有的资源,通过super.finalize()方式可以实现从下到上的finalize()方法的调用,即先释放自己的资源,再去释放父类的资源。        

       但是,不要在程序中频繁的调用垃圾回收,因为每一次执行垃圾回收,jvm都会强制启动垃圾回收器运行,这会耗费更多的系统资源,会与正常的Java程序运行争抢资源,只有在执行大量的对象的释放,才调用垃圾回收最好。

4)public static long currentTimeMillis(){}      

    System.currentTimeMillis();  --> 返回当前时间(以毫秒为单位)

public class S{
    public static void main(String[] args){
        long startTime=System.currentTimeMillis();
        int a=0;
        for(int i=0;i<1000000000;i++){
            a+=i;
        }
        long endTime=System.currentTimeMillis();
        System.out.println("执行此程序用了"+(endTime-startTime)+"毫秒。");
    }
}
执行此程序用了380毫秒。

5)public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length){}    

     将指定源数组中的数组从指定位置复制到目标数组的指定位置。

public class S{
    public static void main(String[] args){
        int[] a=new int[]{1,2,3,10,20,30,4,5,6};
        int[] b=new int[3];
        System.arraycopy(a,3,b,0,3);
        for(int i=0;i<b.length;i++){
            System.out.print(b[i]+" ");
        }
}
10  20  30       
a表示数组a, 3表示 a 数组坐标(10),b表示数组b,0 表示 b 数组的坐标 0,3表示拷贝的长度。

 

二、RunTime类

 

1、RunTime类概述

      每个Java应用程序都有一个Runtime类实例,它允许应用程序与运行应用程序的环境进行交互。可以从getRuntime方法获取当前运行时。

 

2、Java Runtime类的方法

1)public static Runtime getRuntime(): 此方法返回与当前Java应用程序关联的实例或Runtime对象。

// Java program to illustrate getRuntime()
// method of Runtime class
public class GFG
{
    public static void main(String[] args)
    {
        // get the current runtime assosiated with this process
        Runtime run = Runtime.getRuntime();
        // print the current free memory for this runtime
        System.out.println("" + run.freeMemory());
    }
}


输出:
124130416

2)public long freeMemory():此方法返回JVM(Java虚拟机)中的可用内存量

// Java program to illustrate freeMemory()
// method of Runtime class
public class GFG
{
    public static void main(String[] args)
    {
        // print the number of free bytes
        System.out.println("" + Runtime.getRuntime().freeMemory());
    }
}


输出:
124130416

3)public long totalMemory():此方法返回JVM(Java虚拟机)中的总内存量

// Java program to illustrate totalMemory()
// method of Runtime class
public class GFG
{
    public static void main(String[] args)
    {
        // print the number of total bytes
        System.out.println("" + Runtime.getRuntime().totalMemory());
    }
}


输出:
124780544
 

 

4)public Process exec(String command)抛出IOException:此方法在单独的进程中执行给定的命令。

     异常:

            SecurityException:如果存在安全管理器且其checkExec方法不允许创建子进程

            IOException:如果发生I / O错误

            NullPointerException:如果command为null

            IllegalArgumentException:如果命令为空

// Java program to illustrate Process exec()
// method of Runtime class
public class GFG
{
    public static void main(String[] args)
    {
        try
        {
            // create a process and execute google-chrome
            Process process = Runtime.getRuntime().exec("google-chrome");
            System.out.println("Google Chrome successfully started");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}



输出:
Google Chrome successfully started
 

注意:替换为您要启动的任何软件。在Linux上工作,google-chrome只是这样编写的。在windows / mac中可能有所不同。

 

5)public void addShutdownHook(Thread hook):此方法注册一个新的虚拟机JVM Shutdown Hook线程。

     异常:

        IllegalArgumentException:如果已经注册了指定的挂钩,或者可以确定挂钩已在运行或已经运行

        IllegalStateException:如果虚拟机已经在关闭的过程中

        SecurityException: 如果安全管理器拒绝RuntimePermission(“shutdownHooks”)

// Java program to illustrate addShutdownHook()
// method of Runtime class
public class GFG
{
    // a class that extends thread that is to be called when program is exiting
    static class Message extends Thread
    {
        public void run()
        {
            System.out.println("Program exiting");
        }
    }
    public static void main(String[] args)
    {
        try
        {
            // register Message as shutdown hook
            Runtime.getRuntime().addShutdownHook(new Message());
            // cause thread to sleep for 3 seconds
            System.out.println("Waiting for 5 seconds...");
            Thread.sleep(5000);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}



输出:
Waiting for 5 seconds...
Program exiting

 

 

6)public boolean removeShutdownHook(Thread hook):

      此方法取消注册先前注册的JVM Shutdown Hook虚拟机关闭挂钩。

// Java program to illustrate removeShutdownHook()
// method of Runtime class
public class GFG
{
    // a class that extends thread that is to be called when program is exiting
    static class Message extends Thread
   {
       public void run()
        {
            System.out.println("Program exiting");
        }
    }

    public static void main(String[] args)
    {
        try
        {
            Message p = new Message();
            // register Message as shutdown hook
            Runtime.getRuntime().addShutdownHook(p);
            
            // cause thread to sleep for 3 seconds
            System.out.println("Waiting for 5 seconds...");
            Thread.sleep(5000);
            
            // remove the hook
            Runtime.getRuntime().removeShutdownHook(p);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }
}



输出:
Waiting for 5 seconds...
 

7)public int availableProcessors():此方法返回JVM(Java虚拟机)可用的处理器数。

// Java program to illustrate availableProcessors()
// method of Runtime class
public class GFG
{
    public static void main(String[] args)
    {
        // check the number of processors available
        System.out.println("" + Runtime.getRuntime()
                                    .availableProcessors());
         
    }
}


输出:
4

8)public void exit(int status):此方法通过启动其关闭序列来终止当前运行的Java虚拟机。

// Java program to illustrate availableProcessors()
// method of Runtime class
public class GFG
{
    public static void main(String[] args)
    {
        // check the number of processors available
        System.out.println("" + Runtime.getRuntime()
                                    .availableProcessors());
         
    }
}


输出:
4

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值