Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Thread By Name

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?

like image 563
NullPointer Avatar asked Mar 12 '13 19:03

NullPointer


People also ask

How do I get thread ID?

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.

What does thread currentThread () return?

currentThread. Returns a reference to the currently executing thread object.

What is thread currentThread () getName ()?

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.


2 Answers

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; } 
like image 164
VicVu Avatar answered Sep 25 '22 02:09

VicVu


You can find all active threads using ThreadGroup:

  • Get your current thread's group
  • Work your way up the threadgroup hierarchy by calling ThreadGroup.getParent() until you find a group with a null parent.
  • Call 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).

like image 38
parsifal Avatar answered Sep 22 '22 02:09

parsifal