Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminating thread using thread Id in java

Tags:

java

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 ?

like image 726
Vishvesh Phadnis Avatar asked Oct 06 '14 09:10

Vishvesh Phadnis


People also ask

How do you terminate a thread in Java?

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.

How do you stop a thread from another thread in Java?

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.

How do you destroy a thread?

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.

Which method is used for threads to terminate?

A thread can also explicitly terminate itself or terminate any other thread in the process, using a mechanism called cancelation.


1 Answers

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();
    }
}
like image 52
akash Avatar answered Oct 05 '22 06:10

akash