[java] スレッド名取得2

スレッド名を取得するためのクラス

package ***.***.***;

import java.io.PrintWriter;

public class ThreadListener {
    /**
     * ルートスレッドグループを探して、再帰的にリストアップします。
     * 
     * @param out
     */
    public static void listAllThreads(PrintWriter out) {
        ThreadGroup currentThreadGroup;
        ThreadGroup rootThreadGroup;
        ThreadGroup parent;

        // 現在のスレッドグループを取得
        currentThreadGroup = Thread.currentThread().getThreadGroup();

        // ここでルートスレッドグループを探す
        rootThreadGroup = currentThreadGroup;
        parent = rootThreadGroup.getParent();
        while (parent != null) {
            rootThreadGroup = parent;
            parent = parent.getParent();
        }

        // 再帰的にリスト
        printGroupInfo(out, rootThreadGroup, "");
    }

    /**
     * スレッドグループとそのスレッド及びグループに関する情報を表示します。
     * 
     * @param out
     * @param rootThreadGroup
     * @param string
    */
    private static void printGroupInfo(PrintWriter out, ThreadGroup rootThreadGroup, String string) {
        if (rootThreadGroup == null) {
            return;
        }

        int numThreads = rootThreadGroup.activeCount();
        int numGroups = rootThreadGroup.activeGroupCount();
        Thread[] threads = new Thread[numThreads];
        ThreadGroup[] groups = new ThreadGroup[numGroups];

        rootThreadGroup.enumerate(threads, false);
        rootThreadGroup.enumerate(groups, false);

        System.out.println("^^^^^" + string + "Thread Group: " + rootThreadGroup.getName() + " Max priority: " + rootThreadGroup.getMaxPriority() + (rootThreadGroup.isDaemon() ? "Daemon" : ""));

       for (int i = 0; i < numThreads; i++) {
            printThreadInfo(out, threads[i], string + "     ");
       }
       for (int i = 0; i < numGroups; i++) {
           printGroupInfo(out, groups[i], string + "     ");
       }
   }

   /**
    * スレッドに関する情報を表示します。
    * 
    * @param out
    * @param thread
    * @param string
    */
   private static void printThreadInfo(PrintWriter out, Thread thread, String string) {
       if (thread == null) {
            return;
        }
        System.out.println("~~~~~" + string + "Thread: " + thread.getName() + " Prority: " + thread.getPriority() + (thread.isDaemon() ? " Daemon" : "") + (thread.isAlive() ? "" : " Not Alive"));
    }
}
最終更新:2010年07月13日 11:42
ツールボックス

下から選んでください:

新しいページを作成する
ヘルプ / FAQ もご覧ください。