2014-02-24 59 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();