Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 996
Raji Avatar asked Nov 05 '09 13:11

Raji


2 Answers

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.

like image 104
abyx Avatar answered Sep 19 '22 17:09

abyx


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.

like image 27
Brian Agnew Avatar answered Sep 19 '22 17:09

Brian Agnew