---
title: "线程的各种异常信息"
author: "arne3166"
date: "2010-10-14T11:41:51Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-10-14T11:41:51Z"
id: 784648
url: "https://arne3166.iteye.com/blog/784648"
---

```
import java.io.*;

public class ThreadInfo {
	static PrintWriter out = new PrintWriter(System.out, true);
	public static void main(String[] args) {
		Thread[] threads = new Thread[4];
		ThreadGroup group = new ThreadGroup ("MyThreadGroup");
		if(args.length > 0) {
			Thread thread = Thread.currentThread();
			thread.setName(args[0]);	
		}
		for(int i = 0; i< 4; i++) {
			threads[i] = new Thread(group,"MyThread#" + i);
		}
		ThreadInfo.printAllThreadInfo();
	}
	public static void printAllThreadInfo() {
		ThreadGroup parent,root;
		root = parent = Thread.currentThread().getThreadGroup();
		while((parent = parent.getParent()) != null) {
			root = parent;
		}
		out.println();
		printThreadGroupInfo(" ",root);
	}
	public static void printThreadGroupInfo (String indent, ThreadGroup group) {
		final int SAFETY = 5;
		if(group == null) {
			return ;
		}
		out.println(indent + "ThreadGroupt" + group.getName() + "; Max Priority: " +
			  group.getMaxPriority() + (group.isDaemon() ? " [Daemon] " : ""));
		int numThreads = group.activeCount();
		Thread[] threads = new Thread[numThreads + SAFETY];
		numThreads = group.enumerate(threads,false);
		for(int i = 0; i< numThreads; i++) {
			printThreadInfo(indent + " ", threads[i]);
		}
		int numGroups = group.activeGroupCount();
		ThreadGroup[] groups = new ThreadGroup[numGroups + SAFETY];
		numGroups = group.enumerate(groups, false);
		for(int i = 0; i< numGroups; i++) {
			printThreadGroupInfo(indent + "  ", groups[i]);
		}
	}
	public static void printThreadInfo (String indent, Thread thread) {
		if(thread == null) {
			return ;
		}
		out.println(indent + "Thread:" + thread.getName() + "; Priority :"
			  + thread.getPriority() + (thread.isDaemon()? "[Daemon]":" ") 
			  + (thread.isAlive()? "[Alive] " :"[NotAlive]") 
			  + ((Thread.currentThread() == thread) ? " <==current " : "" ));
	}
}
```