第五章 Java API(四)

5.2 System类与Runtime类

5.2.1 System类

System类定义了一些与系统相关的属性和方法,它所提供的属性和方法都是静态的。

System类的常用方法

方法名称功能描述
static void exit (int satus)该方法用于终止当前正在运行的Java虚拟机,其中参数status表示状态码,若状态码非0,则表示异常终止
satic void gc运行垃圾回收器,用于对垃圾进行回收
static void currenTimeMillis返回以毫秒为单位的当前时间
static void arraycopy (Object src,int srcPos,Object dest,int destPos,int length)从src引用的指定源数组复制到dest引用的数组,复制从指定位置开始,到目标数组的指定位置结束
static Properties getProperties()取得当前的系统属性
static String getProperty(String key)获取指定键描述的系统属性

1.arraycopy()方法

arraycopy()方法用于将数组从源数组复制到目标数组,声明格式如下:

static void arraycopy (Obiect src,int srcPos,Object dest,int destPos,int length)

关于声明格式中参数的相关介绍如下:

  • src:表示源数组
  • dest:表示目标数组
  • srcPos:表示源数组中复制元素的起始位置
  • destPos:表示复制到目标数组的起始位置
  • length:表示复制元素的个数

在进行数组复制时,目标数组必须有足够的空间来存放复制的元素,否则会发生角标越界异常。如下,演示数组元素对象复制。

案例学习5-10

public class Example10 {
	public static void main(String[] args) {
		int[] fromArray = { 10, 11, 12, 13, 14, 15 }; // 源数组
		int[] toArray = { 20, 21, 22, 23, 24, 25, 26 }; // 目标数组
		System.arraycopy(fromArray, 2, toArray, 3, 4); // 拷贝数组元素
		// 打印拷贝后数组的元素
          System.out.println("拷贝后的数组元素为:");
		for (int i = 0; i < toArray.length; i++) {
			System.out.println(i + ": " + toArray[i]);
		}
	}
}

 运行结果→

复制后的数组元素为:

0:20

1:21

2:22

3:12

4:13

5:14

6:15

 2.currentTimeMillis()方法

currentTimeMillis()方法用于获取当前系统的时间,返回值是long类型的值,该值表示当前时间与1970年1月1日0点0分0秒之间的时间差,单位是毫秒,通常也将该值称为时间戳。

计算for循环求和所消耗的时间→

public class Example11 {
	public static void main(String[] args) {
		long startTime = System.currentTimeMillis();
// 循环开始时的当前时间
		int sum = 0;
		for (int i = 0; i < 1000000000; i++) {
			sum += i;
		}
		long endTime = System.currentTimeMillis();
// 循环结束后的当前时间
		System.out.println("程序运行的时间为:"+(endTime - startTime)+"毫秒");
	}
}

 运行结果→

程序运行的时间为:245毫秒 

3.getProperties()和getProperty()方法

System类的getProperties()方法用于获取当前系统的全部属性,该方法会返回一个Properties对象,其中封装了系统的所有属性,这些属性是以键值对形式存在的。

getProperties()方法用于根据系统的属性名获取对应的属性值。

4.gc()方法

一个对象在成为垃圾后会暂时保留在内存中,当这样的垃圾堆积到一定程度后,Java虚拟机就会启动垃圾回收期将这些垃圾对象从内存中释放,从而使程序获得更多可用的内存空间。

除了等待Java虚拟机进行自动垃圾回收外,还可以通过调用System.gc()方法通知Java虚拟机立即进行垃圾回收。

如下演示Java虚拟机进行垃圾回收的过程→

案例学习5-13

class Person {
	// 下面定义的finalize方法会在垃圾回收前被调用
	public void finalize() {
		System.out.println("对象将被作为垃圾回收...");
	}
}
public class Example13{
   public static void main(String[] args) {
		// 下面是创建了两个Person对象
		Person p1 = new Person();
		Person p2 = new Person();
		// 下面将变量置为null,让对象成为垃圾
		p1 = null;
		p2 = null;
		// 调用方法进行垃圾回收
		System.gc();
         for (int i = 0; i < 1000000; i++) {
			// 为了延长程序运行的时间
		}
	}
}

5.2.2 Runtime类

Runtime类用于表示虚拟机运行时的状态,它用于封装Java虚拟机进程。

 每个Java应用程序都有一个Runtime类实例,它允许应用程序与运行应用程序的环境进行交互。

可以从getRuntime方法获取当前运行时。

表5-5 Runtime类的常用方法

方法声明功能描述
getRuntime()该方法用于返回当前应用程序的运行环境
exec(String command)该方法用于根据指定的路径执行对应的可执行文件
freeMemory()该方法用于返回Java虚拟机中的空闲内存量,以字节为单位
maxMemory()该方法用于返回Java虚拟机的最大可用内存量
availableProcessors()该方法用于返回当前虚拟机的处理器个数
totalMemory()该方法用于返回Java虚拟机中的内存总量

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值