すでに述べたように、最善の方法はこれを自分で追跡することです。これにより、自分が何をしているのかを明確に理解することができます。スレッドで作業する場合は良いことです...うーん...すべての場合に良いことです;)。
しかし、本当にスレッドを検出したい場合は、 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;
}
}