gpt4 book ai didi

java - 获得线程的控制权然后杀死它

转载 作者:行者123 更新时间:2023-12-01 17:36:06 25 4
gpt4 key购买 nike

我有一个关于 Java 线程的问题。在我的代码中,

...
client.doSth();
// now need to get hold of the thread that is initiated by 'client'
(get a reference to the 'client' thread)
// now kills it
(kills the 'client' thread)
...

所以我想知道的是:在第一个括号中,如何以编程方式获取对“客户端”线程(而不是程序运行的主线程)的引用,在第二个括号中,我如何正确地杀死它,即不使用折旧的 stop() 方法。

非常感谢。

最佳答案

要显示线程树,请这样做:

你可以这样做:

// Find the root thread group
ThreadGroup root = Thread.currentThread().getThreadGroup().getParent();
while (root.getParent() != null) {
root = root.getParent();
}

// Visit each thread group
visit(root, 0);

// This method recursively visits all thread groups under `group'.
public static void visit(ThreadGroup group, int level) {
// Get threads in `group'
int numThreads = group.activeCount();
Thread[] threads = new Thread[numThreads*2];
numThreads = group.enumerate(threads, false);

System.out.println(" ");

// Enumerate each thread in `group'
for (int i=0; i<numThreads; i++) {
// Get thread
Thread thread = threads[i];
System.out.println(thread.toString());
}

// Get thread subgroups of `group'
int numGroups = group.activeGroupCount();
ThreadGroup[] groups = new ThreadGroup[numGroups*2];
numGroups = group.enumerate(groups, false);

// Recursively visit each subgroup
for (int i=0; i<numGroups; i++) {
visit(groups[i], level+1);
}

}

您可以选择调用显示指定线程 ID 的 stackTrace 的方法:

 System.out.println(thread.dumpStack());

现在你有了要杀死的 id :

int idToKill = 2;
int active = Thread.activeCount();
System.out.println("currently active threads: " + active);
Thread all[] = new Thread[active];
Thread.enumerate(all);
for (int i = 0; i < active; i++) {
System.out.println(i + ": " + all[i]);
if(idToKill == i)
((Thread) all[i]).interrupt();
}

关于java - 获得线程的控制权然后杀死它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6175915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com