How to stop a thread?

Solution 1:

In general, you don't forcibly stop threads because it's dangerous. You set a flag that tells the thread in question to exit from it's thread loop under controlled circumstances.

Your thread loop looks something along these lines:

void run() {
  while (shouldContinue) {
    doThreadWorkUnit();
  }
}

And somewhere else you set the shouldContinue variable and wait for the thread to finish:

...
thread.shouldContinue = false;
thread.join();
...

(All this is likely not correct Java, since I don't do Java. View it as pseudo code and modify for your actual language/thread library/etc.)

Solution 2:

Here's what the Java people have to say about why not to call thread.stop and what to do instead.

http://download.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

The short answer is, you allow the thread entry point function to return.

Solution 3:

Better you have to use this method of thread,to stop it.

Thread.interrupt();

So that you can also save the state of thread.