通过Id获取一个主题

ofl*_*ofl 9 java jmx

我在JMX java中工作,我通过使用getAllThreadIds ()接口的方法获取所有线程ID,ThreadMXBean但我需要一种方法来杀死给定ID的线程.例如:

    ThreadMXBean tbean;
    tbean = ManagementFactory.getThreadMXBean();
    long[] IDs=tbean.getAllThreadIds();
    //.... i need a way to kill the Threads wich have this IDs
Run Code Online (Sandbox Code Playgroud)

请帮助我谢谢

Ren*_*ink 9

你可以试试这个:

public void printAllThreadIds() {
    Thread currentThread = Thread.currentThread();
    ThreadGroup threadGroup = getRootThreadGroup(currentThread);
    int allActiveThreads = threadGroup.activeCount();
    Thread[] allThreads = new Thread[allActiveThreads];
    threadGroup.enumerate(allThreads);

    for (int i = 0; i < allThreads.length; i++) {
        Thread thread = allThreads[i];
        long id = thread.getId();
        System.out.println(id);
    }
}

private static ThreadGroup getRootThreadGroup(Thread thread) {
    ThreadGroup rootGroup = thread.getThreadGroup();
    while (true) {
        ThreadGroup parentGroup = rootGroup.getParent();
        if (parentGroup == null) {
            break;
        }
        rootGroup = parentGroup;
    }
    return rootGroup;
}
Run Code Online (Sandbox Code Playgroud)

但你应该打断一个Thread而不是stop它.

该Thread.stop()方法已弃用,因为它会立即杀死该方法Thread.因此,当前由此更改的数据结构Thread可能保持不一致状态.中断使线程有机会正常关闭.


Jun*_*san 2

java中实际上没有杀死线程的好方法。曾经有一个名为 Thread.stop() 的 api,但它也已被弃用。检查此链接以了解 Thread.stop 为何不好以及我们应该如何停止线程的更多详细信息。

http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

仅获取线程 ID 对您没有帮助,您需要拥有线程对象引用来设置标志来停止该线程。