首页 新闻 赞助 找找看

请教关于thread构造方法的一个小问题

0
[已解决问题] 解决于 2017-09-20 18:50
package test;
public class Test0919 
{
    public static void main(String args[])
    {
        A a=new A("t1");
    }
}

class A implements Runnable
{
    Thread t=null;
    String tname=null;
    public A(String tname)
    {
        this.tname=tname;
        this.t=new Thread(this, tname);
        this.t.start();
    }
    @Override
    public void run() 
    {
        try 
        {
            for(int i=0;i<20;i++)
            {
                System.out.println(this.t.getName());
                this.t.sleep(300);
            }
        } 
        catch (InterruptedException e) 
        {
            e.printStackTrace();
        }
    }
}
构造一个线程

为什么将A类中构造方法中线程的构造方法改为thread(tname)控制台就不打印线程名称啦

package test;
public class Test0919 
{
    public static void main(String args[])
    {
        A a=new A("t1");
    }
}

class A implements Runnable
{
    Thread t=null;
    String tname=null;
    public A(String tname)
    {
        this.tname=tname;
        this.t=new Thread(tname);
        this.t.start();
    }
    @Override
    public void run() 
    {
        try 
        {
            for(int i=0;i<20;i++)
            {
                System.out.println(this.t.getName());
                this.t.sleep(300);
            }
        } 
        catch (InterruptedException e) 
        {
            e.printStackTrace();
        }
    }
}
View Code
窦光大大存大大凯的主页 窦光大大存大大凯 | 菜鸟二级 | 园豆:220
提问于:2017-09-19 19:27
< >
分享
最佳答案
0

我觉得之所以不打印是因为你执行start方法的线程并不是A,因为你在构造里面是新new出来的一个Thread,它start,并不代表A里面的run方法会执行。我也没测试过,如果楼主有正确答案不妨告知下。

奖励园豆:5
让我发会呆 | 老鸟四级 |园豆:2929 | 2017-09-20 11:38

因为 thread(this,name),指的是给this绑定一个线程叫“name”,然后这个this在这个代码中指的就是new出来的a这个实例对象。这样是可以运行start()的run()方法的。

当thread(name)只是new了一个叫|“name”的线程,并不知道在哪,并不在a这个对象实例中。

窦光大大存大大凯 | 园豆:220 (菜鸟二级) | 2017-09-20 18:53

@窦光大大存大大凯: 我也是这么认为的,哈哈……

让我发会呆 | 园豆:2929 (老鸟四级) | 2017-09-20 18:55
其他回答(1)
0

构造函数吧Thread 的参数穿进去,public A(String tname,Thread t)

Drunk_fish | 园豆:178 (初学一级) | 2017-09-29 21:45
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册