2012-02-12 20 views
2

我正在用Java編寫多線程服務器應用程序。 一切工作正常,但有一個小問題。 當我停止監聽傳入連接請求的runnable時,套接字保持存在。所以我的問題是:如何停止一個可運行的對象並清理在這個可運行的對象中創建的所有對象?Java:使用套接字清理可運行對象

停止線程的代碼:

Runnable tr = new Worldwide() ; 
     Thread thread = new Thread(tr) ; 
     thread.start() ; 
     online = true ; 

     while (core.getServerSate()) { 
      try{ 
      Thread.sleep(200); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } ; 
     thread.stop() ; 
     thread. 
     core.printToConsole("Server is offline now") ; 

可運行的代碼:

public class Worldwide implements Runnable { 

Core core = Core.getInstance() ; 

public Worldwide() { 

} 
@Override 
public void run() { 

    try { 
    ServerSocket server = new ServerSocket(port) ; 

    core.printToConsole("Server is online") ; 
    core.printToConsole ("listening on port :" + server.getLocalPort()) ; 
    while (core.getServerSate() == true) { 

     Socket client = server.accept() ; 
     Runnable tr = new ClientCommunication(client) ; 
     new Thread (tr).start() ; 

    } 

    } 
    catch(Exception e) { 
     core.printToConsole ("An error occured while going online") ; 
     e.printStackTrace() ; 
    } 
    } 

謝謝,湯姆

+0

不要使用'Thread.stop'。此方法已被棄用。相反,最好使用'Thread.interrupt'並將您的循環邏輯基於線程的中斷狀態。當你捕捉中斷時,你需要傳播它。 – mre 2012-02-12 14:55:33

+0

我想這對我不起作用,因爲循環停在Socket client = server.accept(); – tb96 2012-02-12 15:20:13

回答

2

您可以從主線程關閉套接字。這會打斷電話accept並導致它拋出IOException。然後您可以從IOException的捕獲中退出接受線程的run方法。

+0

謝謝你的答案。但是我怎樣才能從主線程關閉套接字? – tb96 2012-02-12 16:09:32

+0

@ tb96。您必須在主線程中創建套接字並將其傳遞給工作線程。這樣你在兩個線程中都有套接字對象,你可以在工作線程中調用'accept'並在主線程中調用'close'。 – Tudor 2012-02-12 17:22:31

+0

謝謝,這是我需要的答案:) – tb96 2012-02-12 18:08:35

1

你需要通過調用close - 方法明確關閉的ServerSocket插座。最好的做法是在Worldwide類的run-方法中使用finally -block(即使發生異常,套接字也會關閉)。

+0

感謝您的回答。 – tb96 2012-02-12 18:52:55