如前所述,最好的方法是自己跟踪。这迫使您清楚地了解自己在做什么。如果你使用线程是一件好事......嗯......在任何情况下都是一件好事;)。
但是,如果您真的想检测线程,您可以使用 Thread 类的反射来获取所需的信息。首先使方法“getThreads”可访问以获取所有正在运行的线程,然后使字段“target”可访问以获取线程的可运行对象。
这是一个示例程序(但我建议不要在实际应用程序中使用。您现在应该启动什么线程,它可能会损害与未来 JDK 的兼容性,可能会损害可移植性......):
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
Runnable myRunnable = new Runnable() {
@Override
public void run() {
try {
System.out.println("Start: " + Thread.currentThread().getName());
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
};
Thread one = new Thread(myRunnable);
Thread two = new Thread(myRunnable);
one.start();
two.start();
List<Thread> threads = getThreadsFor(myRunnable);
for (Thread thread : threads)
System.out.println("Found: " + thread.getName());
}
private static List<Thread> getThreadsFor(Runnable myRunnable) throws Exception {
Method getThreads = Thread.class.getDeclaredMethod("getThreads");
Field target = Thread.class.getDeclaredField("target");
target.setAccessible(true);
getThreads.setAccessible(true);
Thread[] threads = (Thread[]) getThreads.invoke(null);
List<Thread> result = new ArrayList<Thread>();
for (Thread thread : threads) {
Object runnable = target.get(thread);
if (runnable == myRunnable)
result.add(thread);
}
return result;
}
}