How to Get a Reference to a Java Thread

How to Get a Reference to a Java Thread thumbnail
Get a Reference to a Java Thread

Running code under Java threads is a powerful way to get a lot done in a short time. To monitor and control the threads, you need to set up a thread object tied to your thread-enabled code. This gives you full control over the threads you created.

Things You'll Need

  • Java project with runnable threads in the code
Show More

Instructions

    • 1

      Get the thread ID with this command inside the mandatory run() function that executes your thread:

      Thread.currentThread().getId()

    • 2

      Assign the thread object to a public variable if you need to control the thread from other parts of the program, or print it out directly if you just want to know what's running:

      public int myThreadId = 0;

      public void run () {

      System.out.println("Thread Name: " + Thread.currentThread().getName(); // Printing the thread name

      myThreadId = Thread.currentThread().getId(); // Assigning the thread ID to a public variable

      }

    • 3

      Create a new thread object to control or monitor a thread from other parts of the program. You can also grab the object from an outside thread, such as the main process, by building a complete tree of running threads and thread groups. Call this from the main() function of your Java class:

      // Walk down the tree to find the root group

      ThreadGroup myRootGroup = Thread.currentThread( ).getThreadGroup( );

      ThreadGroup parentGroup;

      while ( ( parentGroup = myRootGroup.getParent() ) != null ) {

      rootGroup = parentGroup;

      }

      // Walk back up from the root, creating a Thread object for every thread in your process

      Threads[] myThreads = new Thread[ myRootGroup.activeCount() ];

      while ( rootGroup.enumerate( myThreads, true ) == myThreads.length ) {

      myThreads = new Thread[ myThreads.length * 2 ];

      }

      Now you can access every thread in your process one by one. For example:

      System.out.println("Thread Name: " + myThreads[0].currentThread().getName();

      myThreadId = myThreads[0].currentThread().getId();

Related Searches:

References

Resources

  • Photo Credit code image by charles taylor from Fotolia.com

Comments

You May Also Like

Related Ads

Featured