【发布时间】:2021-10-01 17:06:02
【问题描述】:
以下代码给了我 NullPointerException。
class MT extends Thread{
public void run(){
}
}
public class ThreadGroupDemo{
public static void main(String[] args) throws InterruptedException{
MT t = new MT();
t.start();
Thread.sleep(5000);
System.out.println(t.getName());
//^^^^This line gives the thread name
System.out.println(t.getThreadGroup().getName());
//^^^^This line is giving me NullPointerException
}
}
这段代码的最后一行给出了 NullPointerException。
【问题讨论】:
-
线程对象仍然存在。线程组为空,因为线程已死。见docs.oracle.com/javase/8/docs/api/java/lang/…
-
但是当我评论
Thread.sleep(5000);时,它给了我main作为线程组名称。 -
因为在这种情况下线程还没有死。
-
看起来
t.getThreadGroup()返回 null。检查一下。
标签: java multithreading nullpointerexception java-threads threadgroup