Tutorial :How do I kill a thread from another thread in Java?



Question:

I am calling two threads from a main thread, call them thread 1 and thread 2. When thread 1 stops, I want to stop or kill thread 2 also. How can I do this?There is a change in actual output what i want.That is There is a main class which is also thread.From main class i am calling thread1 and thread2.I am giving an input to thread1 from main class but when this input is getting changed i want to kill the running thread1 and start it once again with another input.The second thread,thread2 will run with the output given by the thread1.So eventually when the first thread is killed the second will be running but will give an output only if t6here is an input for that thread.


Solution:1

Java has deprecated methods for explicitly killing another thread (like Thread.stop / Thread.destroy). The right way is to make sure the operations on the other thread can handle being told to stop (for example, they expect an InterruptedException, which means you can call Thread.interrupt() in order to stop it).

You might also be interested in setting the second thread as a daemon thread, which means that in case all other threads in the VM have finished then the process will exit.


Solution:2

See this Java Specialist article on how to shut down threads cleanly.

Briefly, the article recommends Thread.interrupt() plus the appropriate InterruptedException handling in the thread code. That's an interesting discussion in itself, and something I rarely see done correctly.


Solution:3

According to these instructions, it's best to use flag variables to tell the other thread to stop its work cleanly.


Solution:4

In the run() method of your thread, check an attribute that is set through an accessor method like shutdown() when you want to stop the thread, use that value to end the while loop. For example:

boolean stopping = false;    Thread currentThread = null;    public void run() {        currentThread = Thread.currentThread();        while (!isStopping()) {            // do something, sleep a while      }  }    public synchronized void shutdown() {        stopping = true;        currentThread.notifyAll();  }    public synchronized boolean isStopping() {        return stopping;  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »