Get reference to Thread Object from its ID

前端 未结 2 1694
慢半拍i
慢半拍i 2020-12-31 00:02

How can I get reference to a Running Thread if I know the ID associated with that Thread?

e.g.

long threadID = 12342;
Thread thread          


        
2条回答
  •  天涯浪人
    2020-12-31 00:24

    You have 2 ways to do it. Both are quite simple:

    • Old way: get the root thread group you may access Thread.currentThread().getGroup()..getParent() in loop. and call enumerate(Thread[])

    • newer (slower though). for (Thread t : Thread.getAllStackTraces().keySet()) if (t.getId()==id)...

    The first method has a small problem that due to a bug in ThreadGroup.destroy(), a ThreadGroup may not enumerate anything at all.

    The second is slower and has a security flaw, though.

提交回复
热议问题