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
2 回答

慕的地8271018
TA貢獻1796條經驗 獲得超4個贊
我覺得之所以不打印是因為你執行start方法的線程并不是A,因為你在構造里面是新new出來的一個Thread,它start,并不代表A里面的run方法會執行。我也沒測試過,如果樓主有正確答案不妨告知下。
添加回答
舉報
0/150
提交
取消