I want to terminate thread using it's Id.
using below statement I'm getting thread. this thread Id I'm maintaining in Hashtable
,but whenever use want to terminate the thread it will be possible for me to termiate using thread Id.
long threadId=Thread.currentThread().getId();
How can I achieve it ?
Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java. This method stops the execution of a running thread and removes it from the waiting threads pool and garbage collected. A thread will also move to the dead state automatically when it reaches the end of its method.
In Java Threads, if any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException.
Modern ways to suspend/stop a thread are by using a boolean flag and Thread. interrupt() method. Using a boolean flag: We can define a boolean variable which is used for stopping/killing threads say 'exit'. Whenever we want to stop a thread, the 'exit' variable will be set to true.
A thread can also explicitly terminate itself or terminate any other thread in the process, using a mechanism called cancelation.
You can do it like this,
//Give you set of Threads
Set<Thread> setOfThread = Thread.getAllStackTraces().keySet();
//Iterate over set to find yours
for(Thread thread : setOfThread){
if(thread.getId()==yourThread.getId()){
thread.interrupt();
}
}
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