Get a thread by Id

。_饼干妹妹 提交于 2019-12-08 16:15:03

问题


I worked in JMX java and I get all the thread IDs by using the getAllThreadIds () method of the interface ThreadMXBean but I need a way to kill the thread of a given ID. for example:

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

plz help me Thanks


回答1:


You can try this:

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;
}

But you should interrupt a Thread and not stop it.

The Thread.stop() method is deprecated, because it immediately kills a Thread. Thus data structures that are currently changed by this Thread might remain in a inconsistent state. The interrupt gives the Thread the chance to shutdown gracefully.




回答2:


There is actually no good way to kill a thread in java. There used be an api called Thread.stop() but it is also deperecated. Check this link for more details why Thread.stop was bad and how we should be stopping a thread.

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

Getting just the thread id will not help you, you need to have the thread object reference to set a flag to stop that thread.




回答3:


You can use this method:

static Map<Thread,StackTraceElement[]>  getAllStackTraces()

to get all threads, then traverse map by key and find appropriate thread.

But this is a very bad approach. How are you going to stop thread? Using void stop() method? Id suggest using Executor framework in conjunction with interruption mechanism.




回答4:


Thread.getAllStackTraces returns all stack traces of all live threads Map<Thread,StackTraceElement[]>. These are supposed to be the same threads that ThreadMXBean returns. You can extract threads from this map and interrupt them. Note that there is no legal method in Java to kill a thread.



来源:https://stackoverflow.com/questions/18224253/get-a-thread-by-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!