Roshan Jayawardana
Roshan Jayawardana

Reputation: 107

How to terminate the execution of thread in java?

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?

Upvotes: 1

Views: 172

Answers (3)

user207421
user207421

Reputation: 310957

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.

Upvotes: 2

sam
sam

Reputation: 83

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

Upvotes: -1

HAL9000
HAL9000

Reputation: 3761

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
        }
    }
}

Upvotes: 2

Related Questions