2011-04-20 168 views
1

我試圖清理應用程序中的資源,然後關閉它,從我以前的問題(Detecting When A Java Application Closes)開始我已經實現了以下代碼完美地執行清理操作。在調用System.exit(0)後應用程序繼續運行 - Java

//Intercept when the application closes 
      Runtime.getRuntime().addShutdownHook(new Thread() 
      { 
       @Override 
       public void run() 
       { 
        //Reclaim resources from MIDI usage 
        if(_midiInstance.CleanUp()) 
        { 
         Logger.Add("Closed resources successfully on ShutDown"); 
        } 
        else 
        { 
         Logger.Add("Failed to close all resources on ShutDown"); 
        } 
        System.exit(0); 
       } 
      }); 

雖然System.exit(0);調用被理解和處理,應用程序繼續運行,只是沒有可見的GUI。我曾考慮過將System.exit(0)調用放在線程之外,但它超出了範圍,沒有任何其他線程或流正在運行。

當連接到ShutDown事件以確保一切關閉時,是否需要執行額外的步驟?

感謝您的時間,我非常感謝。

+0

應用程序中的所有線程是否正確處理被中斷? – justkt 2011-04-20 18:56:33

+0

應用程序中沒有其他線程,唯一的線程是鉤入Shutdown事件時聲明的線程。 – 2011-04-20 19:15:02

回答

3

看完您的其他問題後,您的窗口似乎不會撥打dispose()。如果屬實,那將解釋您的問題的原因。

+0

在調用System.exit(0)之前,我會調用Dispose()嗎? – 2011-04-20 19:15:31

+0

你可以調用它而不是調用System.exit(0)。該應用程序將自然退出。 – JVerstry 2011-04-20 19:23:00

+0

@Jamie Keeling它解決了你的問題嗎? – JVerstry 2011-04-20 20:44:26

1

您需要通過乘坐窗口關閉按鈕:

  //overriding the windowClosing() method will allow the user to click the close button 
    addWindowListener(
      new WindowAdapter() 
    { 
     public void windowClosing(WindowEvent e) 
     { 
      System.exit(0); 
     } 
    }); 

通過這樣的程序將關閉不只是變得不可見。

+0

是的,但如果在其他線程上執行工作,則這是一種苛刻的方法。它並沒有給他們一個很好的清理機會。 – JVerstry 2011-04-20 19:24:57

+0

我同意dispose()是比System.exit(0)更好的選擇;我真的指出了windowsClosing的覆蓋 – Bit 2011-04-20 19:50:09

相關問題