Java 关于ThreadGroup
我尝试创建一个实现Runnable的类。我希望当我创建该类的对象时,我也可以分配一个ThreadDrop。但是这两个代码之间的结果不同。为什么?非常感谢 这是codeAJava 关于ThreadGroup,java,multithreading,Java,Multithreading,我尝试创建一个实现Runnable的类。我希望当我创建该类的对象时,我也可以分配一个ThreadDrop。但是这两个代码之间的结果不同。为什么?非常感谢 这是codeA public class ThreadDemo implements Runnable { private String groupname; private boolean terminated=true; ThreadGroup threadGroup1=new ThreadGroup(grou
public class ThreadDemo implements Runnable {
private String groupname;
private boolean terminated=true;
ThreadGroup threadGroup1=new ThreadGroup(groupname);
ThreadDemo(String groupname){
this.groupname=groupname;
}
....
我是codeB
public class ThreadDemo implements Runnable {
private boolean terminated=true;
ThreadGroup threadGroup1;
ThreadDemo(String groupname){
threadGroup1 = new ThreadGroup(groupname);
}
....
我使用codeA和codeB创建对象
public static void main(String[] args) {
ThreadDemo td=new ThreadDemo("group");
Thread threadA = new Thread(td.threadGroup1,td);
out.println(threadA.getThreadGroup().getName());
threadA.start();
td.terminate();
threadA.interrupt();
}
codeA的结果是
空的
codeB的控制台是
团体
在codeA中,您的组名为空:
private String groupname; // this is null by default
private boolean terminated=true;
ThreadGroup threadGroup1=new ThreadGroup(groupname); // you pass null in here
在codeB中,在构造函数中传递组的名称:
ThreadGroup threadGroup1;
ThreadDemo(String groupname){
threadGroup1 = new ThreadGroup(groupname); // gets the name from the parameter
}
因为属性的构建时间早于construtor,所以如果
private String groupname;
private boolean terminated=true;
ThreadGroup threadGroup1=new ThreadGroup(groupname);
ThreadDemo(String groupname){
this.groupname=groupname;
在创建之前,您将得到null sine属性“String groupname”为null
ThreadGroup threadGroup1=新的ThreadGroup(groupname) 在codeA中,您正在将线程组名称作为null传递给线程组 请参阅下面的链接,它将清除您对对象初始化的想法/疑虑
为什么?您可以随时通过
thread.currentThread().getThreadGroup().getName()
获取当前线程的线程组的名称。你不需要这些,我明白了!!谢谢你的回答!!