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();
}
}
}
構(gòu)造一個(gè)線程
為什么將A類中構(gòu)造方法中線程的構(gòu)造方法改為thread(tname)控制臺(tái)就不打印線程名稱啦
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
2 回答

慕的地8271018
TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
我覺得之所以不打印是因?yàn)槟銏?zhí)行start方法的線程并不是A,因?yàn)槟阍跇?gòu)造里面是新new出來的一個(gè)Thread,它start,并不代表A里面的run方法會(huì)執(zhí)行。我也沒測(cè)試過,如果樓主有正確答案不妨告知下。

慕哥9229398
TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超6個(gè)贊
構(gòu)造函數(shù)吧Thread 的參數(shù)穿進(jìn)去,public A(String tname,Thread t)
添加回答
舉報(bào)
0/150
提交
取消