Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get reference to Thread Object from its ID

Tags:

How can I get reference to a Running Thread if I know the ID associated with that Thread?

e.g.

long threadID = 12342; Thread thread = (What goes here?) getThreadFromId(threadID); //I know this is totally made up 
like image 574
SamRowley Avatar asked Jul 12 '11 16:07

SamRowley


People also ask

What is thread currentThread () getId () in Java?

In the run() method, we use the currentThread(). getName() method to get the name of the current thread that has invoked the run() method. We use the currentThread(). getId() method to get the id of the current thread that has invoked the run() method.

How can we get the reference of current thread of the method?

The java. lang. Thread. currentThread() method returns a reference to the currently executing thread object.

What is thread currentThread () getName ()?

Thread. currentThread() returns a reference to the thread that is currently executing. In the above example, I've used thread's getName() method to print the name of the current thread.

How do you find the thread ID?

ThreadId can be obtained from the Thread. currentThread() method.


1 Answers

You have 2 ways to do it. Both are quite simple:

  • Old way: get the root thread group you may access Thread.currentThread().getGroup()..getParent() in loop. and call enumerate(Thread[])

  • newer (slower though). for (Thread t : Thread.getAllStackTraces().keySet()) if (t.getId()==id)...

The first method has a small problem that due to a bug in ThreadGroup.destroy(), a ThreadGroup may not enumerate anything at all.

The second is slower and has a security flaw, though.

like image 191
bestsss Avatar answered Sep 30 '22 01:09

bestsss