我对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)
...
所以我想知道的是:在第一个括号中,我如何以编程方式获取对'client'线程的引用(不是程序运行的主线程),在第二个括号中,如何正确杀死它,即不使用折旧的stop()方法。
非常感谢。
答案 0 :(得分:2)
要显示Thread树,请执行以下操作:
你可以这样做:// 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);
}
}
您可以选择调用显示指定Thread 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();
}
答案 1 :(得分:1)
你可以在你的客户端创建一个stpSth()方法并调用它来阻止它
public class Client(){
private Thread t;
volatile private boolean stop;//volatile to ensure visibility across threads
public doSth(){
stop=false;
Runnable r = new Runnable(){
@Override
public void run(){
while(!stop){
//do stuff and periodically and ensure that interrupts bubble through
}
}
};
t = new Thread(r);
t.start();
}
public void stopSht(){
stop=true;
t.interupt();
}
}
答案 2 :(得分:1)
编辑:
重新阅读问题后,如果您有权访问客户端代码,我不再确定。如果你这样做,你可以修改它,甚至不使用线程,但java.util.concurrent.ExecutorService
或类似的......但
由于代码不是您自己的......您可以自行阻止代码。
ThreadGroup类是专为。管理部分程序或模块并不容易,通常需要一些已经建立的框架。确保一些第三方代码会表现得很好并且并不总是可行的。它应该包括上下文类加载器,什么不是,但这里是一个如何完成它的脱脂版本。
仍然可能有一些事情可以打破入侵者的骨头。假设已经使用了stop()/ close()等,在日志记录期间会有一些像ThreadDeath这样的技巧,等等。
ThreadGroup g=new ThreadGroup("client X group");
Runnable r=new Runnable(){
public void run(){
client.doSmth();//assuming a new thread is started...
}
}
Thread t= new Thread(g, r, "clientStarter");
t.start();
//stopping, last resort code, it's usually more complicated than just thread.stop, though
//now you can enumerate threads of the ThreadGroup
synchronized(g){//sync ensures no more threads will be created, use it w/ extreme caution
Thread[] threads = new Thread[g.activeCount()];
for(Thread thread:threads){
if(thread==null) break;
thread.stop();//
//cannot join in sync of ThreadGroup, do not use it here
}
}
祝你好运!
答案 3 :(得分:1)
我在comment中看到您使用的是kryonet API。
kryonet为Client对象提供了stop()方法。如果使用start()启动客户端创建一个Thread,stop()应该停止它。
以下是启动和停止kryonet服务器和客户端的代码段,显示进程中各个点的活动线程。 2秒钟的睡眠是让线程在请求停止时结束。
import java.io.IOException;
import java.util.Arrays;
import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.Server;
public class KryonetAndThreads {
public static void main(String[] args) throws IOException,
InterruptedException {
Server s = new Server();
s.start();
s.bind(1927);
printThreads("server started");
Client c = new Client();
c.start();
c.connect(5000, "LOCALHOST", 1927);
printThreads("client connected");
Server s1 = s;
s.stop();
printThreads("server stopped");
s = new Server();
s.start();
s.bind(1928);
printThreads("new server started"); // new server thread will be last on
// the list.
c.stop();
printThreads("client stopped");
c.start();
c.connect(5000, "localhost", 1928);
printThreads("client connected to second server");
c.stop();
s.stop();
s1.stop();
printThreads("both stopped");
}
private static void printThreads(String message)
throws InterruptedException {
// tick:
Thread.sleep(2000L);
Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads);
System.out.println(message + " : " + Arrays.asList(threads));
}
}
答案 4 :(得分:0)
如果doSth()
方法返回Thread对象,则可以执行以下操作;
Thread t = client.doSth();
t.interrupt();