在java中杀死线程

时间:2012-03-18 18:02:24

标签: java multithreading sockets network-programming

我创建一个服务器客户端程序,客户端将某些信息发送到服务器并从服务器获得相应的响应。 为了从多个客户端持续监听,我在服务器中有一个连续监听客户端请求的线程。无论何时收到请求,我都会启动另一个线程并发送该套接字以运行并开始侦听其他客户端请求。

这是持续监听的代码

while(true){
    //serverListener is a ServerSocket object
    clientSocket = serverListener.accept();//Waiting for any client request

    //New thread started when request is received from any client
    Thread thread =new Thread(new serverThread(clientSocket), "ClientThread");
    thread.start();
}

现在我的问题是如何停止服务器。我知道在while循环中使用boo lean变量然后更改值的另一种方法,但问题是当线程在等待获取任何连接的时候,更改布尔变量的值也不会停止服务器。 / p>

有没有办法解决这个问题。

3 个答案:

答案 0 :(得分:3)

通常,serverListener(我假设实际上是ServerSocket或其他东西)被另一个线程关闭。这将在java.net.SocketException中生成accept(),它将终止循环和线程。

final ServerSocket serverSocket = new ServerSocket(8000);
new Thread(new Runnable() {
    public void run() {
        while (true) {
            try {
                serverSocket.accept();
            } catch (IOException e) {
                return;
            }
        }
    }
}).start();
Thread.sleep(10000);
serverSocket.close();

答案 1 :(得分:0)

ServerSocket #setSoTimeout()可能是您感兴趣的,如果达到超时,将放弃接受。请注意捕获SocketTimeoutException。

答案 2 :(得分:0)

volatile boolean finishFlag = false;

while(true){

            clientSocket = serverListener.accept();//Waiting for any client request

            if ( finishFlag ) 
               break;

            //New thread started when request is received from any client
            Thread thread =new Thread(new serverThread(clientSocket), "ClientThread");
            thread.start();
}

修改

用于中断监听器,你应该从外面停止这个线程,然后accept()将抛出IOException

    try {  
      while (true) {   
        Socket connection = server.accept( );

        try {    
          // any work here    
          connection.close( );
       }
       catch (IOException ex) {
         // maybe the client broke the connection early.
       }

       finally {
       // Guarantee that sockets are closed when complete. 
       try {
          if (connection != null) connection.close( );
       }
       catch (IOException ex) {}
    }    
  }    
  catch (IOException ex) {
    System.err.println(ex);
  }