System 类包含一些有用的类字段和方法。它不能被实例化。
成员方法 | 功能 |
---|---|
static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) | 从src源数组的srcPos索引开始,复制length个元素,从destPost位置开始将这些元素放至到dest数组中 |
static long currentTimeMillis() | 返回以毫秒为单位的当前时间 |
static void exit(int status) | 终止当前正在运行的 Java 虚拟机 |
static void gc() | 运行垃圾回收器 |
示例1
public class Test1 {
public static void main(String[] args) {
int[] src = {1, 2, 3, 4, 5};
int[] dest = new int[5];
System.arraycopy(src, 2, dest, 1, 2);
for (int i = 0; i < dest.length; i++) {
System.out.print(dest[i] + "、");
}
}
}
示例2
//这个毫秒的时间是相对时间,相对于1970-1-1 00:00:00
public class Test2 {
public static void main(String[] args) {
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
System.out.println(i);
}
long end = System.currentTimeMillis();
System.out.println(end - start + "毫秒");
}
}
示例3
public class Test3 {
public static void main(String[] args) {
for (int i = 0; i < 100000; i++) {
System.out.println(i);
if (i == 100) {
System.exit(0);
}
}
}
}
示例4
class Demo {
@Override
protected void finalize() throws Throwable {
System.out.println("我被回收了!");
}
//finalize():当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法
}
public class Test4 {
public static void main(String[] args) {
new Demo();
System.gc();
}
}
调用gc方法暗示着Java虚拟机做了一些努力来回收未用对象,以便能够快速地重用这些对象当前占用的内存。当控制权从方法调用中返回时,虚拟机已经尽最大努力从所有丢弃的对象中回收了空间。所以不一定会把垃圾对象回收。调用System.gc()
实际等效于调用Runtime.getRuntime().gc()
。