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?

Roshan Jayawardana
  • 107
  • 1
  • 2
  • 7
  • 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,562
  • 3
  • 25
  • 47
  • You can use `Thread.interrupt()` to better effect here, and `Thread.isInterrupted(),` and save the extra boolean and method. But none of this will unblock `ServerSocket.accept().` – user207421 Feb 10 '14 at 03:15
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
  • 305,947
  • 44
  • 307
  • 483
-1

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

sam
  • 83
  • 1
  • 7