Kill thread group by name - Java java.lang

Java examples for java.lang:Thread

Description

Kill thread group by name

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String name = "java2s.com";
        killThreadGroup(name);/*w  w w .ja  va2  s  .c o m*/
    }

    /**
     * Kill thread group by name
     *
     * @param name
     */
    public static void killThreadGroup(String name) {
        ThreadGroup threadGroup = getThreadGroupByName(name, null);
        if (threadGroup != null) {
            threadGroup.stop();
        }
    }

    /**
     * Get thread group by name
     *
     * @param name
     * @param root
     * @return thread group or null
     */
    private static ThreadGroup getThreadGroupByName(String name,
            ThreadGroup root) {
        if (root == null) {
            root = getRootThreadGroup();
        }

        int num_groups = root.activeGroupCount();
        ThreadGroup[] groups = new ThreadGroup[num_groups];
        root.enumerate(groups, false);

        for (int i = 0; i < num_groups; i++) {
            ThreadGroup threadGroup = groups[i];
            if (name.equals(threadGroup.getName())) {
                return threadGroup;
            } else {
                threadGroup = getThreadGroupByName(name, threadGroup);
                if (threadGroup != null) {
                    return threadGroup;
                }
            }
        }
        return null;
    }

    /**
     * Get root thread group
     *
     * @return root thread group
     */
    private static ThreadGroup getRootThreadGroup() {
        ThreadGroup root = Thread.currentThread().getThreadGroup();
        ThreadGroup parent = root.getParent();
        while (parent != null) {
            root = parent;
            parent = parent.getParent();
        }
        return root;
    }
}

Related Tutorials