---
title: "Java 获取当前所有的线程"
author: "trinityblood"
date: "2012-08-03T13:02:40Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2012-08-03T13:02:40Z"
id: 1618181
url: "https://trinityblood.iteye.com/blog/1618181"
---

```java

ThreadGroup group = Thread.currentThread().getThreadGroup();
ThreadGroup topGroup = group;
// 遍历线程组树，获取根线程组
while (group != null) {
	topGroup = group;
	group = group.getParent();
}
// 激活的线程数加倍
int estimatedSize = topGroup.activeCount() * 2;
Thread[] slackList = new Thread[estimatedsize];
// 获取根线程组的所有线程
int actualSize = topGroup.enumerate(slackList);
// copy into a list that is the exact size
Thread[] list = new Thread[actualsize];
System.arraycopy(slackList, 0, list, 0, actualSize);
System.out.println("Thread list size == " + list.length);
for (Thread thread : list) {
	System.out.println(thread.getName());
}

```