I have a multithreaded application and I assign a unique name to each thread through setName()
property. Now, I want functionality to get access to the threads directly with their corresponding name.
Somethings like the following function:
public Thread getThreadByName(String threadName) { Thread __tmp = null; Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]); for (int i = 0; i < threadArray.length; i++) { if (threadArray[i].getName().equals(threadName)) __tmp = threadArray[i]; } return __tmp; }
The above function checks all running threads and then returns the desired thread from the set of running threads. Maybe my desired thread is interrupted, then the above function won't work. Any ideas on how to incorporate that functionality?
The pthread_self() function is used to get the ID of the current thread. This function can uniquely identify the existing threads. But if there are multiple threads, and one thread is completed, then that id can be reused. So for all running threads, the ids are unique.
currentThread. Returns a reference to the currently executing thread object.
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. Every thread has a name. you can create a thread with a custom name using Thread(String name) constructor.
An iteration of Pete's answer..
public Thread getThreadByName(String threadName) { for (Thread t : Thread.getAllStackTraces().keySet()) { if (t.getName().equals(threadName)) return t; } return null; }
You can find all active threads using ThreadGroup:
ThreadGroup.getParent()
until you find a group with a null parent.ThreadGroup.enumerate()
to find all threads on the system.The value of doing this completely escapes me ... what will you possibly do with a named thread? Unless you're subclassing Thread
when you should be implementing Runnable
(which is sloppy programming to start with).
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