在我的主要方法中,我完成了以下操作:
ThreadGroup human = new ThreadGroup("Humans");
Thread s = new Thread(human, new Student(ca));
当我通过 System.out.println(s.getThreadGroup().getName()); 打印出线程所在组的名称时,它会打印出人类。但是,当我转到 Student 类并执行以下操作: String threadGroupName = this.getThreadGroup().getName();
并打印出 String 变量时,它会打印出 main
。我不明白这一点,因为在创建这个线程时,我已指定它位于人类线程组中,那么为什么它说它位于主线程组中?
最佳答案
s 是您创建的新线程。而您的 Student 实例是 s.target
当您运行 Thread 构造函数来创建 s 时,您注入(inject)了新的 Runnable (在您的例子中为 Student 实例)。
Thread s = new Thread(人类, new Student(ca));
s 是线程 x,Student 是线程 y。它们是单独的实例。
s.target 是您创建的新 Runnable Student。
希望这有帮助。
如果您想拥有相同的线程组,则必须将“Humans”线程组传递到学生线程中。试试这个:
public class ThreadGroups {
public static void main(String[] args){
ThreadGroup human = new ThreadGroup("Humans");
Thread s1 = new Student(human, "studentThread");
Thread s = new Thread(human, s1);
System.out.println(s.getThreadGroup().getName());
System.out.println(s1.getThreadGroup().getName());
s.start();
}
static class Student extends Thread {
@Override
public void run() {
System.out.println(this.getThreadGroup().getName());
}
public Student(ThreadGroup group, String name) {
super(group, name);
}
public Student() {
}
}
}
关于java - 如何获取当前线程所在线程组的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47611884/