在 Java 中命名线程

java 8server side programmingprogramming

Java 提供了更改线程名称的方法。这些方法定义在 ‘java.lang.Thread’ 类中。可以通过将线程名称作为参数传递给函数来直接设置线程名称。如下所示。 −

示例

import java.io.*;
class name_a_thread extends Thread {
   name_a_thread(String name) {
      super(name);
   }
   @Override
   public void run() {
      System.out.println("Thread is currently running ");
   }
}
public class Demo {
   public static void main (String[] args) {
      name_a_thread thr_1 = new name_a_thread("Joe");
      name_a_thread thr_2 = new name_a_thread("Billy");
      System.out.println("Name of thread 1 is : " + thr_1.getName());
      System.out.println("Name of thread 2 is : " + thr_2.getName());
      thr_1.start();
      thr_2.start();
   }
}

输出

Name of thread 1 is : Joe
Name of thread 2 is : Billy
Thread is currently running
Thread is currently running

解释

名为"name_a_thread"的类扩展了父类 Thread。它定义了一个以字符串为参数的构造函数,并使用"super"函数调用该构造函数。"run"函数被重写,并在控制台上显示相关消息。名为"Demo"的类包含主函数,其中创建了"name_a_thread"类的两个实例,并分别将两个字符串作为参数传递。借助"getName"函数,线程名称显示在控制台上。现在,借助"start"函数,两个线程已启动。


相关文章