public final void setName(String name)
public final String getName()
当使用Runnable创建线程时,Runnable中并没有getName和setName,那么想要获取运行当前代码的线程名字就需要调用 Thread类中的public static Thread currentThread()获取当前线程,在调用getName()获取线程名

 
 public class ThreadName {
    public static void main(String args[]){
        Thread t = new Thread(new MyThreadName(),"线程A");
        t.start();
        t.run();
    }
}
class MyThreadName implements  Runnable{
    @Override
    public void run() {
        System.err.println("threa-name="+Thread.currentThread().getName());
    }
}
     

结果:
threa-name=main
threa-name=线程A

相关文章:

  • 2021-06-25
  • 2021-11-20
  • 2022-01-21
  • 2022-12-23
  • 2021-07-18
  • 2022-01-03
  • 2022-12-23
  • 2021-12-29
猜你喜欢
  • 2022-12-23
  • 2021-06-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-05
  • 2021-10-22
相关资源
相似解决方案