取得线程的方法
public final void setName(String name)设置线程的方法
由于线程运行的不确定性,因此,取得线程的名字是取得当前线程的名字,取的当前线程的方法是
public static Thread currentThread()示例代码如下
package com.li; public class ThreadNameTest { public static void main (String[] args){ ThreadNameTest test = new ThreadNameTest(); ThreadNameTest.MyThread t1 = test.new MyThread(); ThreadNameTest.MyThread t2 = test.new MyThread(); ThreadNameTest.MyThread t3 = test.new MyThread(); //设置线程的名字 t1.setName("线程一"); t2.setName("线程二"); t3.setName("线程三"); //启动线程 t1.start(); t2.start(); t3.start(); } class MyThread extends Thread{ public void run(){ System.out.println("当前线程的名字为:" + Thread.currentThread().getName()); } } }输出的是
当前线程的名字为:线程三 当前线程的名字为:线程一 当前线程的名字为:线程二但要注意的是,可能每次输出的顺序不太一样