How to find the name of the parent thread?

I know that we can have “parents” and “children” when we talk about processes. But is it possible to get a parent name Thread?

I did my research but found the answer only for .Net


Edit: I tried setting the names:

public class Main {

    public static void main(String[] args) {
        Thread r = new ThreadA();
        r.start();
    }

}



public class ThreadA extends Thread {
    public void run() {
        Thread.currentThread().setName("Thread A");
        System.out.println("Here  " + Thread.currentThread().getName());
        Thread r = new ThreadB();
        r.setName(Thread.currentThread().getName());
        r.start();
    }
}

public class ThreadB extends Thread {
    public void run() {
        Thread.currentThread().setName("Thread B");
        System.out.println("Here " + Thread.currentThread().getName());
        Thread r = new ThreadC();
        r.setName(Thread.currentThread().getName());
        r.start();
    }
}

public class ThreadC extends Thread {
    public void run() {
        Thread.currentThread().setName("Thread C");
        System.out.println("Here " + Thread.currentThread().getName());
    }
}
+5
source share
3 answers

As John said, no one knows which thread his parent thread should know. This is important because if every child has a link to the thread that branched them, this would mean many unnecessary thread structures stored in memory. The structure of the parent stream could not be restored by the GC or reused if the child had a link to it.

, , , , Thread.

, , , " ". ThreadGroup s. , :

ThreadGroup threadGroup = new ThreadGroup("mythreadgroup");
Thread thread = new Thread(threadGroup, new Runnable() {...});
...
// then you can do such methods as
threadGroup.enumerate(...);

. , , .


Edit:

, , " " - RMI.

, . System.currentTimeMillis() RMI . , .

ThreadInfo threadInfo =
    ManagementFactory.getThreadMXBean().getThreadCpuTime(thread.getId()); 

"" , getThreadUserTime(...). , thread-ids , , , , , RMI , .

, RMI , , , , RMI.

, long[] . , .

+7

- "" Java .NET. , .NET, , , , .

EDIT: ... , .

- :

String currentName = Thread.currentThread.name();
Thread thread = new Thread(new RunnableC());
thread.setName("C (started by" + currentName + ")");
thread.start();

, .

, Runnable Thread. , .

+7

, , , , (.. , , "" "" ).

, , InheritableThreadLocal: (, name) .


, (, , , ), , . .

This may allow us, for example, to take a picture of all running threads and find out which of them were launched by our thread, as well as children of these threads, etc. - all their descendants. Should work well for monitoring purposes. Not sure if this will be good for anything else.

+2
source

All Articles