关于ThreadGroup的一些东西

时间:2016-06-02 04:41:39

标签: java multithreading

我尝试创建一个实现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的控制台是

  

3 个答案:

答案 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”为null

ThreadGroup threadGroup1 = new ThreadGroup(groupname);

答案 2 :(得分:0)

codeA 中,您将线程组名称作为 null 传递给ThreadGroup

参考下面的链接,它将清除您对对象初始化的想法/疑问

Initialization blocks, constructors and their order of execution