Get Thread By Name

前端 未结 4 1379
隐瞒了意图╮
隐瞒了意图╮ 2020-12-08 05:12

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

相关标签:
4条回答
  • 2020-12-08 05:16

    That's how I did it on the basis of this:

    /*
        MIGHT THROW NULL POINTER
     */
    Thread getThreadByName(String name) {
        // Get current Thread Group
        ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
        ThreadGroup parentThreadGroup;
        while ((parentThreadGroup = threadGroup.getParent()) != null) {
            threadGroup = parentThreadGroup;
        }
        // List all active Threads
        final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        int nAllocated = threadMXBean.getThreadCount();
        int n = 0;
        Thread[] threads;
        do {
            nAllocated *= 2;
            threads = new Thread[nAllocated];
            n = threadGroup.enumerate(threads, true);
        } while (n == nAllocated);
        threads = Arrays.copyOf(threads, n);
        // Get Thread by name
        for (Thread thread : threads) {
            System.out.println(thread.getName());
            if (thread.getName().equals(name)) {
                return thread;
            }
        }
        return null;
    }
    
    0 讨论(0)
  • 2020-12-08 05:22

    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;
    }
    
    0 讨论(0)
  • 2020-12-08 05:30

    I like the HashMap idea best, but if you want to keep the Set, you can iterate over the Set, rather than going through the setup of converting to an array:

    Iterator<Thread> i = threadSet.iterator();
    while(i.hasNext()) {
      Thread t = i.next();
      if(t.getName().equals(threadName)) return t;
    }
    return null;
    
    0 讨论(0)
  • 2020-12-08 05:31

    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).

    0 讨论(0)
提交回复
热议问题