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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With