在线程创建时,不用预留String变量存储线程名称。。。。
在创建时命名:MyThread(String name) {
thrd = new Thread(this, name);
thrd.start();
}
。。。。不是在创建时,命名的运行结果如下。。
Thread-0是线程的名称,下面是源代码:
package bao;
class MyThread implements Runnable {
String thrdName;
MyThread(String name) {
thrdName = name;
}
public void run() {
System.out.println(thrdName+" startinggg.");
try {
for(int count=0; count<10; count++ ) {
Thread.sleep(400);
System.out.println("In "+thrdName+", count is "+count);
}
}
catch(InterruptedException exc) {
System.out.println(thrdName+" interrupted.");
}
System.out.println(thrdName+" interrupting.");
}
}
class D {
public static void main(String[] args) {
System.out.println("Main thread starting.");
MyThread mt = new MyThread("Child #1");
Thread newThrd = new Thread(mt);
System.out.println(newThrd.getName());
newThrd.start();
System.out.println(newThrd.getName());
for(int i=0; i<50; i++ ) {
System.out.print(".");
try {
Thread.sleep(100);
}
catch(InterruptedException exc) {
System.out.println("Main thread interrupted.");
}
}
System.out.println(newThrd.getName());
System.out.println("Main thread ending.");
}
}