如何获取某个线程池ThreadPoolExecutor executor中的所有线程信息

写个获取某个线程池内所有线程信息的方法,参数是ThreadPoolExector

但是我用Thread.currentThread().getThreadGroup,获取的线程数量超过了这个线程池最大线程数,应该有问题,请问一下正确的应该怎么写

img

望采纳


在 Java 中,通过 ThreadPoolExecutor 对象的 getActiveCount 和 getQueue 方法可以获取线程池中正在执行任务的线程数量和正在等待执行的任务队列。

例如:

ThreadPoolExecutor executor = ...;
int activeCount = executor.getActiveCount();
int queueSize = executor.getQueue().size();

获取线程池中所有线程的信息可以使用 getThreads 方法,这个方法会返回一个 Thread[] 数组,每个元素都是一个线程对象。

例如:

ThreadPoolExecutor executor = ...;
Thread[] threads = new Thread[executor.getPoolSize()];
Thread.enumerate(threads);

如果你想要获取每个线程的信息,可以使用 getName 方法获取线程的名称,使用 getState 方法获取线程的状态。

例如:

ThreadPoolExecutor executor = ...;
Thread[] threads = new Thread[executor.getPoolSize()];
Thread.enumerate(threads);

for (Thread thread : threads) {
    String name = thread.getName();
    Thread.State state = thread.getState();
    // do something with the thread information
}

请注意,线程池的大小可能会动态更改,因此获取线程信息的过程可能会变得复杂。你可以使用 getMaximumPoolSize 方法获取线程池的最大线程数,并根据需要动态调整创建线程数组的大小。

例如:

ThreadPoolExecutor executor = ...;
int maxThreads = executor.getMaximumPoolSize();
Thread[] threads = new Thread[maxThreads];
...

call线程起名字_使用ThreadPoolExecutor,获取线程池中运行的线程的名称
如有帮助望采纳
https://www.baidu.com/link?url=416_iYoHYKW01FsyUOO41-DLZb7cr5b0oWqjXUNjlxnU7aZW5rEw4lrvu7cNeHMflW-W0YkGAoUmaTh05lvCrhdwQKnTZwyPHWCEyEF1ZKq&wd=&eqid=d2abe797011a9dbc000000046395c342

不太明白你的具体需求,你可以看看这篇博客,介绍的挺详细的,简单易懂,相关方法也有较为详细的介绍,希望对您有所帮助
https://blog.csdn.net/liuxiao723846/article/details/108026782

试试这个看看,你获取的group不对

import cn.hutool.core.thread.NamedThreadFactory;

import java.util.concurrent.*;

public class Demo01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        final ScheduledThreadPoolExecutor scheduledThreadPoolExecutor =
                new ScheduledThreadPoolExecutor(10, new NamedThreadFactory("ggg", new ThreadGroup("test"), false));
        for (int i = 0; i < 9; i++) {
            scheduledThreadPoolExecutor.execute(() -> {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        final Future<ThreadGroup> submit = scheduledThreadPoolExecutor.submit(() -> Thread.currentThread().getThreadGroup());
        final ThreadGroup threadGroup = submit.get();
        final Thread[] threads = new Thread[threadGroup.activeCount()];
        final int enumerate = threadGroup.enumerate(threads);
        for (Thread thread : threads) {
            System.out.println(thread.getName());
        }
    }
}