java - 如何获取当前线程所在线程组的名称

标签 java multithreading

在我的主要方法中,我完成了以下操作:

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/

相关文章:

java - 包含 Openshift Java RESTClient 时构建失败

java - 如何在 java 的 SimpleDateFormat 中转义单引号

java - 用鼠标移动图像Java

java - 检测不匹配的字符串

c++ - boost asio stream_descriptor 和 event fd 线程安全

multithreading - Perl服务器中的内存泄漏

java - 程序终止时如何关闭端口?

Java 程序无法执行它写入/tmp 的文件,没有这样的文件或目录

java - 使用 System.out.format 和 System.out.println 进行多线程

android - 在 Android 上使用 Ormlite 进行多线程读取的性能