You can set a stop variable that the thread checks after each connection. Then connect to the stream port to wake it up.
Another approach would be to set a timeout with the call to soTimeout() and check the stop variable after each connection and when the timeout occurs. You probably do not want to set the timeout too short. This means that the thread does not stop immediately, so this may not work for you if a quick shutdown is required.
You can also call close () directly on the ServerSocket, if possible, as mentioned by Mark Peters.
source share