1

think that clients are already connected to a server and it is using multiple threads to serve multiple clients in same time, and server needs to be closed for the new comers and clients are already in the server should not be disturbed. How can we do that?

  • 2
    End your loop accepting new connections. If you want a more detailed answer, then start by showing your code. – JB Nizet Feb 05 '14 at 19:37

3 Answers3

2

do something like this:

public class TheThreadClass extends Thread{
    private bool terminated;

    public void terminate(){
        this.terminate = true;
    }

    @Override
    public void run(){
        while(!terminated){
            // thread code here
        }
    }
}
HAL9000
  • 3,348
  • 3
  • 23
  • 43
2

Just close the ServerSocket. The thread blocked in accept() will throw an IOException: socket closed, on which it should exit. Then no new connections will be accepted, but all existing connections will continue to be serviced.

user207421
  • 298,294
  • 41
  • 291
  • 462
-1

I feel the interrupt() method may be the best and easy way to terminate a thread.

sam
  • 83
  • 1
  • 7