2014-10-09 47 views
0

在哪裏以及如何在一個類中實現addShutdownHook,它沒有主要的方法?這可以用來殺死所有由該類初始化的活動套接字嗎?addShutdownHook的實現

+0

你有沒有看:http://stackoverflow.com/questions/ 8722826 /當我需要調用這個方法運行時getruntime addshutdownhook 這不是真的重複,但我認爲你可以在那裏學習的東西? 另請參見:http://hellotojavaworld.blogspot.se/2010/11/runtimeaddshutdownhook.html – 2014-10-09 06:44:53

+0

@SamuelÅslund:謝謝你的幫助..我已經搜索過它,但沒有得到這個鏈接.. – Atmaram 2014-10-10 11:37:56

+0

@SamuelÅslund:addShutdownHook doesn當我們使用Kill -9命令在Linux中終止服務器時不起作用。任何其他解決方案相同? – Atmaram 2014-10-13 11:52:28

回答

1

這可能爲你工作,

public class AddShutdownHookSample { 
     public void attachShutDownHook(){ 
      Runtime.getRuntime().addShutdownHook(new Thread() { 
       @Override 
       public void run() { 
         System.out.println("Inside Add Shutdown Hook"); 
       } 
      }); 

      System.out.println("Shut Down Hook Attached."); 
     } 
    } 

而且在主要方法:

public static void main(String[] args) { 
    AddShutdownHookSample sample = new AddShutdownHookSample(); 
    sample.attachShutDownHook(); 
    System.out.println("Last instruction of Program...."); 
    System.exit(0); 
} 

描述你正在嘗試做的,並顯示在您擁有的是非常精確的點整件事麻煩這會讓其他人更容易幫助你。

+0

我們可以添加此靜態塊也?? ??正如那樣做.. – Atmaram 2014-10-10 11:21:24

+0

@Atmaram我無法得到你,你的意思是我們可以做其他靜態功能相同。那麼答案是肯定的。 – Asis 2014-10-10 11:24:56

+0

我在說如果我在我們班的靜態塊中添加這部分代碼,它會工作嗎? – Atmaram 2014-10-10 12:04:23

0

下面是一個例子,這可以幫助你

public class RuntimeDemo { 

    // a class that extends thread that is to be called when program is exiting 
static class Message extends Thread { 

    public void run() { 
    System.out.println("Bye."); 
    } 
} 

public static void main(String[] args) { 
    try { 

    // register Message as shutdown hook 
    Runtime.getRuntime().addShutdownHook(new Message()); 

    // print the state of the program 
    System.out.println("Program is starting..."); 

    // cause thread to sleep for 3 seconds 
    System.out.println("Waiting for 3 seconds..."); 
    Thread.sleep(3000); 

    // print that the program is closing 
    System.out.println("Program is closing..."); 


    } catch (Exception e) { 
    e.printStackTrace(); 
    } 
} 
} 
+0

感謝Anptk的幫助..我完成了我的工作.. – Atmaram 2015-07-10 09:14:13

0

就像這樣......

static { 
     Runtime.getRuntime().addShutdownHook (new Thread() { 
       public void run() { 
        server.shutdown(); 
       } 
      }); 
    }