用Java命名线程
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”函数对其进行了调用。功能“运行”被覆盖,相关消息显示在控制台上。名为Demo的类包含主要功能,其中创建了'name_a_thread'类的两个实例,并且分别将两个字符串作为参数传递。在“getName”功能的帮助下,线程的名称显示在控制台上。现在,两个线程在“开始”功能的帮助下开始。