命名线程和当前线程

命名线程

Thread类提供了方法来更改和获取线程的名称。默认情况下,每个线程都有一个名称,例如thread-0、thread-1等。但是我们可以使用setName()方法来更改线程的名称。setName()和getName()方法的语法如下:

public String getName(): is used to return the name of a thread.  
public void setName(String name): is used to change the name of a thread.  

我们还可以在创建新线程时直接设置线程的名称,使用类的构造函数。

命名线程的示例:使用setName()方法

文件名:TestMultiNaming1.java

class TestMultiNaming1 extends Thread{  
  public void run(){  
   System.out.println("running...");  
  }  
 public static void main(String args[]){  
  TestMultiNaming1 t1=new TestMultiNaming1();  
  TestMultiNaming1 t2=new TestMultiNaming1();  
  System.out.println("Name of t1:"+t1.getName());  
  System.out.println("Name of t2:"+t2.getName());  
   
  t1.start();  
  t2.start();  
  
  t1.setName("Sonoo Jaiswal");  
  System.out.println("After changing name of t1:"+t1.getName());  
 }  
}  

输出:

Name of t1:Thread-0
Name of t2:Thread-1
After changing name of t1:Sonoo Jaiswal
running...
running...

命名线程的示例:不使用setName()方法

可以在创建线程时设置线程的名称,而不使用setName()方法。观察以下代码。

文件名:ThreadNamingExample.java

// 一个 Java 程序,展示了如何   
// 设置当时的线程名称   
// 线程的创建    
  
// 导入语句   
import java.io.*;  
  
// ThreadNameClass 是 Thread 类的子类  
class ThreadName extends Thread  
{  
  
// 类的构造函数   
ThreadName(String threadName)  
{  
// 调用构造函数    
// 超类,即 Thread 类。  
super(threadName);  
}  
  
//  覆盖方法 run() 
public void run()  
{  
System.out.println(" The thread is executing....");  
}  
}  
  
public class ThreadNamingExample  
{  
// 主要方法 
public static void main (String argvs[])  
{  
// 创建两个线程并设置它们的名字  
// 使用类的构造函数  
ThreadName th1 = new ThreadName("JavaTpoint1");  
ThreadName th2 = new ThreadName("JavaTpoint2");  
  
// 调用 getName() 方法获取名字    
// 上面创建的线程   
System.out.println("Thread - 1: " + th1.getName());  
System.out.println("Thread - 2: " + th2.getName());  
  
  
//  在两个线程上调用 start() 方法   
th1.start();  
th2.start();  
}  
}  

输出:

Thread - 1: JavaTpoint1
Thread - 2: JavaTpoint2
 The thread is executing....
 The thread is executing....

当前线程

currentThread()方法返回当前正在执行的线程的引用。

public static Thread currentThread()    

currentThread()方法的示例

文件名:TestMultiNaming2.java

class TestMultiNaming2 extends Thread{  
 public void run(){  
  System.out.println(Thread.currentThread().getName());  
 }  
 public static void main(String args[]){  
  TestMultiNaming2 t1=new TestMultiNaming2();  
  TestMultiNaming2 t2=new TestMultiNaming2();  
  
  t1.start();  
  t2.start();  
 }  
}  

输出:

Thread-0
Thread-1

标签: java, Java面试题, Java下载, java教程, java技术, Java学习, Java学习教程, Java语言, Java开发, Java入门教程, Java进阶教程, Java高级教程, Java笔试题, Java编程思想