顯示具有 系統函式 標籤的文章。 顯示所有文章
顯示具有 系統函式 標籤的文章。 顯示所有文章

2010年9月15日 星期三

Java筆記-Finalize 終結物件

System.runFinalization()可用來請求執行finalize
在執行System.gc()時,也會執行finalize()
覆寫finalize()範例 ##ReadMore##

public class MyObject {
    static int count;
    MyObject() {
        ++count;
    }
    public static void main(String[] args) {
        MyObject obj1 = new MyObject();
        MyObject obj2 = new MyObject();
        MyObject obj3 = new MyObject();
        System.out.println("目前有" +count+ "個物件");
        obj2 = null;
        System.out.println("請求G.C.");
        System.gc();
        System.out.println("目前剩餘" +count+ "個物件");
    }
    protected void finalize() throws Throwable {
        --count;
        String tName = Thread.currentThread().getName();
        System.out.println("執行finalize()的是:" + tName);
    }
}

執行結果:
目前有3個物件
請求G.C.
執行finalize()的是:Finalizer
目前剩餘2個物件

Java筆記-System.gc() 記憶體釋放,回收垃圾物件

若程式碼指定物件為null,則會被garbage collector thread回收
請求調用Garbage Collection的函式
System.gc()和Runtime.getRuntime().gc()

2010年4月2日 星期五

JAVA筆記-System.getProperty() 擷取系統參數

執行Java程式時,可輸入自定義的參數

例如:
> java -Dshow=HelloWorld -Dtimes=2 Example

try{
  if (System.getProperty( "times" )!=null){
    //取得字串
    String str = System.getProperty( "show" );
  }
  if (System.getProperty( "times" )!=null){
    //取得數字
    int times = Integer.parseInt(System.getProperty("times"));
  }
} catch (Exception e){}

2010年3月24日 星期三

JAVA筆記-System.exit(1) 強迫程式結束

強迫程式結束
System.exit(1);

正常結束
System.exit(0);

使用其他數字,則會關閉應用程式
System.exit(2);

##ShowAll##
/