简体   繁体   中英

How to terminate Thread spawned from ExecutorService

I have the following problem:

I am running a server, which establishes a TCP connection with all the clients who connect in a separate Thread spawned by ExecutorService . I have an exit command, which should terminate the server including all the threads spawned by ExecutorService . In each particular Thread related to a client I have a while -loop, where I am waiting for client's input in the condition using the InputStream of the associated socket. I also have a global boolean variable, which indicates if the server is online. As soon as it turns to false , I break the loop and terminate the thread. It looks basically like this:

// userInput - String
// in - BufferedReader associated with the input stream of the client's socket
while ((userInput = in.readLine()) != null && serverIsOnline) { 
     //do some stuff
}

However, the problem is that in.readLine() is a blocking operation and therefore the whole server won't be terminated unless all the clients type in something. ExecutorService.shutDownNow() also would not work, as the interrupt is ineffective in this case, because the thread is blocked by another operation. I also want to avoid System.exit() . Any efficient solutions?

Try to close all client sockets. All reading threads should throw IOException in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM