Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

java - Get reference to Thread Object from its ID

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 = (What goes here?) getThreadFromId(threadID); //I know this is totally made up
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...