[問題] 如何在 addShutdownHook 下 interrupt 特定 thread

作者: darkgray (Nobody)   2016-12-20 17:48:07
我在寫一個接收 socket 資料的程式,我想要在 class 之中會一直接收資料直到我按下 ctrl + c。
我的程式碼類似像是這樣
public static void main(String[] args) {
conn = new Connection(payload);
conn.connect();
while(true){
// keep the program listening to the socket data
}
conn.disconnect();
}
我要結束程式碼時,執行 conn.disconnect() 這個方法。
我知道可以藉由
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
conn.disconnect();
}
}
);
得到 ctrl + c 的事件,但我在 block 中,無法得到 conn 這個 instance。
我也嘗試過將整個 main 弄成另外的 Runnable thread,然後再使用 interrupte() 方法,
但我在 addShutdownHooker block 中一樣無法得到我的 thread instance 來處理。
希望大大可以題點一二,謝謝。
作者: ssccg (23)   2016-12-20 21:55:00
JVM關掉OS就會回收所有socket了吧

Links booklink

Contact Us: admin [ a t ] ucptt.com