ITeye博客

线程的各种异常信息

arne3166 · 2010-10-14 11:41 · 多线程 · 编程语言 · Markdown

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 " : "" ));
	}
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。