当前位置: 技术问答>java相关
请教一个小程序的问题(有关finalize的)
来源: 互联网 发布时间:2015-07-26
本文导语: 请看这个程序: class Chair { static boolean gcrun = false; static boolean f = false; static int created = 0; static int finalized = 0; int i; Chair() { i = ++created; if(created == 47) System.out.prin...
请看这个程序:
class Chair {
static boolean gcrun = false;
static boolean f = false;
static int created = 0;
static int finalized = 0;
int i;
Chair() {
i = ++created;
if(created == 47)
System.out.println("Created 47");
}
public void finalize() {
if(!gcrun) {
gcrun = true;
System.out.println(
"Beginning to finalize after " +
created + " Chairs have been created");
}
if(i == 47) {
System.out.println(
"Finalizing Chair #47, " +
"Setting flag to stop Chair creation");
f = true;
}
finalized++;
if(finalized >= created)
System.out.println(
"All " + finalized + " finalized");
}
}
public class Garbage {
public static void main(String[] args) {
while(!Chair.f) {
new Chair();
new String("To take up space");
}
}
}
当finalize()第一次起作用时,为什么变量i是1,而且每次调用finalize()时,i都增加1,但是created已经是很大的数了?
class Chair {
static boolean gcrun = false;
static boolean f = false;
static int created = 0;
static int finalized = 0;
int i;
Chair() {
i = ++created;
if(created == 47)
System.out.println("Created 47");
}
public void finalize() {
if(!gcrun) {
gcrun = true;
System.out.println(
"Beginning to finalize after " +
created + " Chairs have been created");
}
if(i == 47) {
System.out.println(
"Finalizing Chair #47, " +
"Setting flag to stop Chair creation");
f = true;
}
finalized++;
if(finalized >= created)
System.out.println(
"All " + finalized + " finalized");
}
}
public class Garbage {
public static void main(String[] args) {
while(!Chair.f) {
new Chair();
new String("To take up space");
}
}
}
当finalize()第一次起作用时,为什么变量i是1,而且每次调用finalize()时,i都增加1,但是created已经是很大的数了?
|
finalize在java规范中声明是不能保证虚拟机一定调用该方法的,所以尽量不要实现该方法,及时实现,也不要对他期待有什么惊奇出现!