Demo.java:
package cn.xxx.demo; /* * 每个线程,都有自己的名字 * 运行方法main线程,名字就是"main" * 其他新键的线程也有名字,默认 "Thread-0","Thread-1"... * * JVM开启主线程,运行方法main,主线程也是线程,是线程必然就是Thread类对象 * * Thread类中,静态方法 * static Thread currentThread() 返回正在执行的线程对象 */ public class Demo { public static void main(String[] args) { SubThread st = new SubThread(); // 创建子线程 st.setName("旺财"); // 设置子线程名字。 st.start(); // 开启子线程。 /*Thread t =Thread.currentThread(); // 获取正在执行的线程对象。 System.out.println(t.getName());*/ System.out.println(Thread.currentThread().getName()); // 获取当前线程 的名称。 } }SubThread.java(子线程继承Thread类,重写run方法):
package cn.xxx.demo; /* * 获取线程名字,父类Thread方法 * String getName() */ public class SubThread extends Thread{ public SubThread(){ super("小强"); // 通过构造函数,为线程设置名字。 } public void run(){ System.out.println(getName()); // getName() 获取线程名字 (父类Thread的函数) } }