This question already has an answer here:
- How do you kill a Thread in Java? 14 answers
Is there any way to stop another thread from OUTSIDE of the thread? Like, if I ran a thread to run that thread and caused that thread to stop? Would it stop the other thread?
Is there a way to stop the thread from inside without a loop? For example, If you are downloading ideally you would want to use a loop, and if I use a loop I wont be able to pause it until it reaches the end of the loop.
You can create a boolean field and check it inside run:
To stop it just call
This should work.
The recommended way will be to build this into the thread. So no you can't (or rather shouldn't) kill the thread from outside.
Have the thread check infrequently if it is required to stop. (Instead of blocking on a socket until there is data. Use a timeout and every once in a while check if the user indicated wanting to stop)
We don't stop or kill a thread rather we do
Thread.currentThread().isInterrupted().
in main we will do like this:
JavaSun recomendation is to use a shared variable as a flag which asks the background thread to stop. This variable can then be set by a different object requesting the thread to terminate.
You can that way kill the other process, and the current one afterwards.
One possible way is to do something like this:
And when you want to stop your thread, just call a method interrupt():
Of course, this won't stop thread immediately, but in the following iteration of the loop above. In the case of downloading, you need to write a non-blocking code. It means, that you will attempt to read new data from the socket only for a limited amount of time. If there are no data available, it will just continue. It may be done using this method from the class Socket:
In this case, timeout is set up to 50 ms. After this time has gone and no data was read, it throws an SocketTimeoutException. This way, you may write iterative and non-blocking thread, which may be killed using the construction above.
It's not possible to kill thread in any other way and you've to implement such a behavior yourself. In past, Thread had some method (not sure if kill() or stop()) for this, but it's deprecated now. My experience is, that some implementations of JVM doesn't even contain that method currently.