Think in java question

nightsuns 2003-08-18 06:49:43
//: c04:Garbage.java
// Demonstration of the garbage
// collector and finalization

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) {
// The first time finalize() is called:
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) {
// As long as the flag hasn't been set,
// make Chairs and Strings:
while(!Chair.f) {
new Chair();
new String("To take up space");
}
System.out.println(
"After all Chairs have been created:\n" +
"total created = " + Chair.created +
", total finalized = " + Chair.finalized);
// Optional arguments force garbage
// collection & finalization:
if(args.length > 0) {
if(args[0].equals("gc") ||
args[0].equals("all")) {
System.out.println("gc():");
System.gc();
}
if(args[0].equals("finalize") ||
args[0].equals("all")) {
System.out.println("runFinalization():");
System.runFinalization();
}
}
System.out.println("bye!");
}
} ///:~



Created 47
Beginning to finalize after 11167 Chairs have been created
Finalizing Chair #47, Setting flag to stop Chair creation
After all Chairs have been created:
total created = 63762, total finalized = 13992
bye!

在我的机子上面运行之后是这个样子,问:
Beginning to finalize after 11167 Chairs have been created,为什么?不是
47个吗?
...全文
39 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
nightsuns 2003-09-06
  • 打赏
  • 举报
回复
其实你们回答得都不对,
因为现在我知道了!
林中漫步1982 2003-08-20
  • 打赏
  • 举报
回复
如果要立即调用finalize()的话, 可以在把对象标识为垃圾回收后,调用System.gc().

如:
Object object =new Oject();
object=null; //把对象object标识为垃圾回收
System.gc(); //立即调用finalize();
....

hesi726 2003-08-20
  • 打赏
  • 举报
回复
finalize() 什么时候被调用是看你的机器配置以及jvm 的!
只有在JVM觉得内存资源不够时,才会调用垃圾收集器方法!
此时才会调用 finalize()!
看来你的内存不够啊!我的是到 50069 才开始调用 finalize 呢!
另外,finalize() 不一定一定被调用的!
看看你上面的例子就知道,创建了 63762 个对象!只回收了13992 个对象呢!

netyangsu 2003-08-20
  • 打赏
  • 举报
回复
finalize()和new Chairs()是独立的,你这边不停的建立新的对象,但是已经存在的对象到底什么时候回收和finalize()是不确定的,也许你建立一亿个对象,第一个都还没有开始回收
nightsuns 2003-08-20
  • 打赏
  • 举报
回复
为什么没有 人回答问题啊·!
这个问题不会很难吧·!

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧