How to find the name of the parent thread?

前端 未结 4 2042
天涯浪人
天涯浪人 2020-12-04 01:55

I know we can have \'parents\' and \'children\' when we are talking about processes. But is it possible to get parent Thread name?

I did my research, b

4条回答
  •  广开言路
    2020-12-04 02:20

    No - there's no particular concept of a "parent" thread in either Java or .NET. As per the .NET answer you referenced, however, if you're creating the thread yourself you can always give a name which indicates the "creator" thread name within the new thread's name.

    EDIT: Your sample code sets the name before it starts... but then overwrites it after it starts, ignoring the previous name.

    I'd expect something like:

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

    That would be the only place the name of the thread would be set.

    Note that this also uses the idea of implementing Runnable rather than extending Thread. That's a separate matter, but is the preferred approach in most cases.

提交回复
热议问题