Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/**
 * Entity Essentials -- A Component-based Entity System
 *
 * Copyright (C) 2015 Elmar Schug <elmar.schug@jayware.org>,
 *                    Markus Neubauer <markus.neubauer@jayware.org>
 *
 *     This file is part of Entity Essentials.
 *
 *     Entity Essentials is free software; you can redistribute it and/or
 *     modify it under the terms of the GNU Lesser General Public License
 *     as published by the Free Software Foundation, either version 3 of
 *     the License, or any later version.
 *
 *     Entity Essentials is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *     Lesser General Public License for more details.
 *
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

public class Main {
    public static Thread getThreadByName(String name) {
        if (name != null) {
            final Thread[] threads = getAllThreads();

            for (Thread thread : threads) {
                if (thread.getName().equals(name)) {
                    return thread;
                }
            }
        }

        return null;
    }

    public static Thread[] getAllThreads() {
        final ThreadGroup rootThreadGroup = getRootThreadGroup();
        final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

        int nAlloc = threadMXBean.getThreadCount();
        int n = 0;
        Thread[] threads;

        do {
            nAlloc *= 2;
            threads = new Thread[nAlloc];
            n = rootThreadGroup.enumerate(threads, true);
        } while (n == nAlloc);

        return java.util.Arrays.copyOf(threads, n);
    }

    public static ThreadGroup getRootThreadGroup() {
        ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
        ThreadGroup parentThreadGroup;

        while ((parentThreadGroup = threadGroup.getParent()) != null) {
            threadGroup = parentThreadGroup;
        }

        return threadGroup;
    }
}