Java 垃圾收集示范计划没有';不编译
我编写了一个简单的程序来演示垃圾收集。代码如下:Java 垃圾收集示范计划没有';不编译,java,garbage-collection,finalizer,Java,Garbage Collection,Finalizer,我编写了一个简单的程序来演示垃圾收集。代码如下: public class GCDemo{ public static void main(String[] args){ MyClass ob = new MyClass(0); for(int i = 1; i <= 1000000; i++) ob.generate(i); } /** * A class to demonstrate garbage collection and the final
public class GCDemo{
public static void main(String[] args){
MyClass ob = new MyClass(0);
for(int i = 1; i <= 1000000; i++)
ob.generate(i);
}
/**
* A class to demonstrate garbage collection and the finalize method.
*/
class MyClass{
int x;
public MyClass(int i){
this.x = i;
}
/**
* Called when object is recycled.
*/
@Override protected void finalize(){
System.out.println("Finalizing...");
}
/**
* Generates an object that is immediately abandoned.
*
* @param int i - An integer.
*/
public void generate(int i){
MyClass o = new MyClass(i);
}
}
有什么帮助吗?谢谢 Make
MyClass
静态:
static class MyClass {
如果没有这个,您必须有一个
GCDemo
实例才能实例化MyClass
。您没有这样的实例,因为main()
本身是static
您可以大大简化示例。这将做同样的事情,除非你一定会看到消息。在您的示例中,GC可能不会运行,因此在程序退出之前您可能看不到任何内容
while(true) {
new Object() {
@Override protected void finalize(){
System.out.println("Finalizing...");
}
Thread.yield(); // to avoid hanging the computer. :|
}
基本问题是嵌套类需要是静态的。+1
main
处于静态上下文中,因此不能假设存在这样的实例。问题是打印到屏幕非常困难,非常慢,但创建对象的速度要快得多,这意味着处理对象的速度要比清理对象的速度快得多
while(true) {
new Object() {
@Override protected void finalize(){
System.out.println("Finalizing...");
}
Thread.yield(); // to avoid hanging the computer. :|
}