?? ghost.java
字號(hào):
import java.util.Map;
import java.util.HashMap;
public class Ghost {
private static final Map<String,Ghost> ghosts=new HashMap<String,Ghost>();
private final String name;
public Ghost(String name) {
this.name=name;
}
public String getName(){return name;}
public static Ghost getInstance(String name){
Ghost ghost =ghosts.get(name);
if (ghost == null) {
ghost=new Ghost(name);
ghosts.put(name,ghost);
}
return ghost;
}
public static void removeInstance(String name){
ghosts.remove(name);
}
protected void finalize()throws Throwable{
ghosts.put(name,this);
System.out.println("execute finalize");
throw new Exception("Just Test");
}
public static void main(String args[])throws Exception{
Ghost ghost=Ghost.getInstance("IAmBack"); //①
System.out.println(ghost); //②
String name=ghost.getName(); //③
ghost=null; //④
Ghost.removeInstance(name); //⑤
System.gc(); //⑥
//把CPU讓給垃圾回收線程
Thread.sleep(3000); //⑦
ghost=Ghost.getInstance("IAmBack"); //⑧
System.out.println(ghost); //⑨
}
}
/****************************************************
* 作者:孫衛(wèi)琴 *
* 來源:<<Java面向?qū)ο缶幊?gt;> *
* 技術(shù)支持網(wǎng)址:www.javathinker.org *
***************************************************/
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -