62,614
社区成员
发帖
与我相关
我的任务
分享
import java.lang.ref.*;
public class Test
{
public static void main(String[] args)
{
String a = new String("This object is uncollected!");
WeakReference b = new WeakReference(a);
System.out.println(b.get());
//Remove strong reference to the String
a = null;
//Call garbage collector...
System.gc();
//Shouldn't the String be finalized?
if(b.get() == null)
System.out.println("It works!");
else // This is the condition that is executed
System.out.println(b.get());
System.exit(0);
}
}
public class GCTest {
public static void main(String[] args) throws InterruptedException {
Obj obj1 = new Obj();
Obj obj2 = new Obj();
System.out.println("begin.");
Thread.sleep(2000);
obj1 = null;
System.gc();
Thread.sleep(2000);
obj2 = null;
System.gc();
Thread.sleep(2000);
System.out.println("end.");
}
}
class Obj {
public void finalize() {
System.out.println(this + " is finalized.");
}
}