threadinfo.java

来自「讲解在java平台上用AWT编写与图形有关的小程序」· Java 代码 · 共 62 行

JAVA
62
字号
//: ThreadInfo.java

public class ThreadInfo {
	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();
	}
	
	//	list information about all the threads and threads and thread groups
	//	in the application
	public static void printAllThreadInfo() {
		ThreadGroup parent, root;
		//	find the root of all running threads
		root = parent = Thread.currentThread().getThreadGroup();
		while ( (parent = parent.getParent()) != null )
			root = parent;
		//	print information recursively from the root
		System.out.println();
		printThreadGroupInfo("",root);
	}
	
	//	print information about a thread group
	public static void printThreadGroupInfo(String indent,ThreadGroup group) {
		if ( group == null )
			return;
		System.out.println(indent+
			"THREAD GROUP:"+group.getName()+
			";Max Priority: "+group.getMaxPriority()+
			(group.isDaemon()?"[Daemon]":""));
		//	print information about component threads
		int no_of_threads = group.activeCount();
		Thread[] threads = new Thread[no_of_threads];
		no_of_threads = group.enumerate(threads,false);
		for ( int i=0; i<no_of_threads; i++ )
			printThreadInfo(indent+" ",threads[i]);
		//	print information about component thread groups
		int no_of_groups = group.activeGroupCount();
		ThreadGroup[] groups = new ThreadGroup[no_of_groups];
		no_of_groups = group.enumerate(groups,false);
		for ( int i=0; i<no_of_groups; i++ )
			printThreadGroupInfo(indent+" ",groups[i]);
	}
	
	//	print information about a single thread
	public static void printThreadInfo(String indent, Thread thread) {
		if ( thread == null )
			return;
		System.out.println(indent+
			"THREAD:"+thread.getName()+
			"; Priority:"+thread.getPriority()+
			(thread.isDaemon()?"[Daemon]":"")+
			(thread.isAlive()?"[Alive]":"[NotAlive]")+
			((Thread.currentThread()==thread)?"<==current":""));
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?