我尝试创建一个实现Runnable的类。我希望当我创建一个类的对象时,我也可以分配一个threaddroup.But这两个代码之间有不同的结果。为什么?非常感谢。
这是codeA
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的控制台是
基
答案 0 :(得分:1)
在 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
}
答案 1 :(得分:1)
因为该属性早于construtor构建,所以如果你
private String groupname;
private boolean terminated=true;
ThreadGroup threadGroup1=new ThreadGroup(groupname);
ThreadDemo(String groupname){
this.groupname=groupname;
在创建
之前,您将获得null sine属性“String groupname”为nullThreadGroup threadGroup1 = new ThreadGroup(groupname);
答案 2 :(得分:0)
在 codeA 中,您将线程组名称作为 null 传递给ThreadGroup
参考下面的链接,它将清除您对对象初始化的想法/疑问
Initialization blocks, constructors and their order of execution