Get Thread By Name

前端 未结 4 1388
隐瞒了意图╮
隐瞒了意图╮ 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;
    }
    

提交回复
热议问题