// Thread.class
ClassPool pool = ClassPool.getDefault();
CtClass ctClass = pool.get( "java.lang.Thread" );
for (CtMethod ctMethod : ctClass.getDeclaredMethods()) {
if (ctMethod.getName().equals( "init" )) {
// init, ()
ctMethod.insertBefore( "threadQ = currentThread();" );
break ;
}
}
// javaagent
String agentPath = "/path/javaageent.jar" ;
VirtualMachineDescriptor vmd = ...;
VirtualMachine vm = VirtualMachine.attach(vmd);
vm.loadAgent(agentPath);
// Thread.class
ClassDefinition classDef = new ClassDefinition(Thread. class , ctClass.toBytecode());
Agent.redefineClasses(classDef);
//
Field parentThreadField = Thread. class .getDeclaredField( "threadQ" );
parentThreadField.setAccessible( true );
// 10
for ( int i = 0; i < 10; i++) {
final int n = i;
new Thread( new Runnable() {
public void run() {
try {
Thread.sleep(10000);
System. out .println( "thred #" + n);
} catch (Exception ex) {
}
}
}).start();
}
Thread currentThread = Thread.currentThread();
ThreadGroup threadGroup = currentThread.getThreadGroup();
Thread[] threads = new Thread[threadGroup.activeCount()];
threadGroup.enumerate(threads);
for (Thread t : threads) {
// parentThreadField.get(t)
if (currentThread.equals(parentThreadField.get(t))) {
System. out .println(t);
}
}
* This source code was highlighted with Source Code Highlighter .
Source: https://habr.com/ru/post/74208/