2014-02-24 65 views
-1

我在java中製作藍牙服務器。我有一個JFrame,我想在新線程中運行服務器。當我想停止和/或重新啓動服務器時,問題就會消失。有誰知道一個好的解決方案?是否有可能調用stopServer函數,或者刪除整個服務器實例?作爲java線程的服務器

---//the server class--- 
public class BTServer implements Runnable{ 


protected void run(){ 

    //run server 

} 
protected void stopServer() throws IOException{ 
    //stop the server 
} 

} 

---//the JFrame main class--- 
public class NewJFrame extends javax.swing.JFrame{ 

JButton startButton = new JButton(); 
JButton stopButton = new JButton(); 
Thread server; 

public NewJFrame() { 
    server = new Thread(new BTServer()); 

} 

private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {           
    server.start(); 
} 

private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {           
    //??? 
} 

public static void main(String args[]) { 

    new NewJFrame().setVisible(true); 
    } 

} 
+0

Dup的實現Runnable具有多類:http://stackoverflow.com/questions/247455/stopping-a-thread-in-java –

回答

0

你需要保持你的可運行的引用,然後停止這種方式。您可以避免通過延長線,而不是用於BTServer

public class BTServer implements Runnable{ 
    private boolean running = true; 
    protected void run(){ 
     while(running) 
     //do something 
    } 
    protected void stopServer() throws IOException{ 
     running = false; 
    } 
} 

public class NewJFrame extends JFrame { 
    //Your original code for variables 
    private BTServer runnable; 
    public NewJFrame() { 
     runnable = new BTServer(); 
     server = new Thread(runnable); 
    } 

    //Your other code 

    private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {           
     runnable.stopServer(); 
    } 
} 
0

如果服務器執行非阻塞檢查在while(true)環,我會發明這將從外部服務器檢查有規律地設置的標誌。如果服務器調用阻塞任務,則必須能夠從外部中斷該任務。

0

我推薦的方式是使用共享變量作爲標誌,要求後臺線程停止。這個變量可以由一個請求線程終止的不同對象來設置。 當線程終止,剛開始新一:

server = new Thread(new BTServer()); 
server.start();