简体   繁体   English

获取控制当前类的java线程

[英]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. 这样做的原因是我想看看是否有不同的线程并行运行它的exectuing代码。

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()的静态方法

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. 从线程角度来看,如果“Do something”部分相同,则Class 1和Class 2是相同的。

In Java, thread is a running entity and class is the procedure that the thread follows. 在Java中,线程是一个正在运行的实体,而类是该线程遵循的过程。 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. 想象一下Java类就像钢琴乐谱一样,线程就像钢琴家一样。 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: 鉴于上面的例子,如果“Do something”部分是相同的,你不需要编写两个不同的类,只需要一个类来完成这项工作:

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

Hope this is useful. 希望这很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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