简体   繁体   中英

Get the java thread controlling the current class

Hi I want to see what thread is running my current class. The reason for this is that I want to see if there are different threads running side by side based on where its exectuing code.

For example:

Public Class one {
   public void Method1 {
       Do something
       print out what thread is running here   
   }
   public void Method2 {
       doing something
   }
}

Class two {
   public void Method1 {
       Do something
       print out what thread is running here   
   }
   public void Method2 {
       doing something
   }
}

I would appreciate if there was something possible.

To access the current thread within the current class, the Thread class has a static method called currentThread()

Thread.currentThread()

This might point you somewhere to giving answers what thread is handling what.

From threading point of view, your Class one and Class two are the same if the "Do something" parts are the same.

In Java, thread is a running entity and class is the procedure that the thread follows. You can not write a class that can only be run by a single thread. Any threads can run any classes.

Imagine Java class like a piano score and threads as pianist. A piano score can be played by more than one pianists, at the same time or at different time.

Given the example above, if the "Do something" parts are the same, you do not need to write two different classes, just one class will do the job:

Public Class ThreadTester {
   public void Method1 {
       System.out.println(Thread.currentThread().getName());
   }
   public void Method2 {
       doing something
   }
}

Hope this is useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM