[java]代码库
public class Test extends Thread {
public void run() {
printMsg(); // 从多线程调用,因此会打印当前线程名字
}
public void printMsg() {
// 获得运行此代码的线程的引用
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("name = " + name);
}
public static void main(String args[]) {
Test t1 = new Test();
Test t2 = new Test();
Test t3 = new Test();
t1.setName("MyThread"); // 设置线程的名称
t1.start();
t2.start();
t3.start();
t1.printMsg(); // 从主线程调用,因此会打印main
t2.printMsg();
t3.printMsg();
}
}
[代码运行效果截图]