java.lang.System
类中提供了大量的静态方法,可以获取与系统相关的信息或系统级操作。
System类私有修饰构造方法,不能创建对象,直接类名调用。
常用方法:
方法名 | 说明 |
public static void exit(int status)
|
终止当前运行的
Java 虚拟机,非零表示异常终止
|
public static long currentTimeMillis()
|
返回当前时间
(
以毫秒为单位
)
|
public static void arrayCopy(Object src, int srcPos, Object dest,int destPos, int length)
|
从指定源数组中复制一个数组
|
public static void gc()
|
运行垃圾回收器。
|
在控制台输出
1-10000
,计算这段代码执行了多少毫秒
public static void main(String[] args) {
//获取当前时间毫秒值
System.out.println(System.currentTimeMillis());
//计算程序运行时间
long start = System.currentTimeMillis();
for (int i = 1; i <= 10000; i++) {
System.out.println(i);
}
long end = System.currentTimeMillis();
System.out.println("共耗时毫秒:" + (end - start));
}
arrayCopy方法:
- Object src:要复制的数据源数组
- int srcPost:数据源数组的开始索引
- Object dest:复制后的目的数组
- int destPos:目的数组开始索引
- int length:要复制的数组元素的个数
将源数组中从1索引开始,复制3个元素到目的数组中
public static void main(String[] args){
int[] src = {1,2,3,4,5};
int[] dest = {6,7,8,9,0};
//将源数组中从1索引开始,复制3个元素到目的数组中
System.arraycopy(src,1,dest,0,3);
for(int i = 0 ; i < dest.length;i++){
System.out.println(dest[i]);
}
}
运行结果:
2
3
4
9
0
gc()方法
运行垃圾回收器,
JVM
将从堆内存中清理对象,清理对象的同时会调用对象的
finalize()
方法,
JVM的垃圾回收器是通过另一个线程开启的,因此程序中的效果并不明显。
public class PersonTestGC {
protected void finalize()throws Throwable{
System.out.println("对象被回收");
}
public static void main(String[] args){
new PersonTestGC();
new PersonTestGC();
new PersonTestGC();
new PersonTestGC();
new PersonTestGC();
new PersonTestGC();
System.gc(); }
}
运行结果(运行到System.gc()方法时,清理之前所有创建的对象,同时调用对象的finalize()方法):
对象被回收
对象被回收
对象被回收
对象被回收
对象被回收
对象被回收