I have a multithreaded server that sits in an infinite loop waiting for new connections and I want to be able to stop this loop when I press Ctrl-C (or something similar). I tried this solution and tried to do something like this:
private void waitForConnections() {
boolean done = false;
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
super.run();
System.err.println("Exiting");
done = true;
}
});
while (!done) {
try {
Socket userSocket = this.serverSocket.accept();
// Faz alguma coisa...
} catch (IOException e) {
e.printStackTrace();
}
}
}
But I can not change the value of the done done variable inside the thread. How can I solve this problem in the simplest and most elegant way?