学无先后,达者为师

网站首页 编程语言 正文

设置线程名称(两种方法)

作者:Qiddo 更新时间: 2023-12-12 编程语言

方式一:通过构造方法设置线程名称。

class SetName1 extends Thread{
  public SetName1(String name){
    super(name);
   }
  @Override
  public void run() {
    System.out.println(this.getName());
   }
}
public class SetNameThread {
  public static void main(String[] args) {
    SetName1 setName1 = new SetName1("SetName1");
    setName1.start();
   }
}

方式二:通过setName()方法设置线程名称。

class SetName2 implements Runnable{
  @Override
  public void run() {
    System.out.println(Thread.currentThread().getName());
   }
}
public class SetNameThread {
  public static void main(String[] args) {
    Thread thread = new Thread(new SetName2());
    thread.setName("SetName2");
    thread.start();
   }
}

原文链接:https://blog.csdn.net/m0_73944607/article/details/130609104

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新