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
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.
The java. lang. Thread. currentThread() method returns a reference to the currently executing thread object.
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.
ThreadId can be obtained from the Thread. currentThread() method.
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.
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