當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Thread setName()用法及代碼示例


線程類的 setName() 方法用於更改線程的名稱。

用法

public final void setName(String a)

參數

a = It shows the new name for the thread.

返回

This method does not return any value.

異常

SecurityException:如果當前線程無法修改線程,則拋出此異常。

示例

public class SetNameExample extends Thread
{  
    public void run()
    {  
        System.out.println("running...");  
    }  
    public static void main(String args[])
    {  
        // creating two threads
        SetNameExample t1=new SetNameExample();  
        SetNameExample t2=new SetNameExample();  
        // start of thread 
        t1.start();  
        t2.start();     
        // change the thread name 
        t1.setName("Sonoo Jaiswal");  
        t2.setName("javatpoint");
        // print the thread after changing 
        System.out.println("After changing name of t1:"+t1.getName());
        System.out.println("After changing name of t2:"+t2.getName());
    }  
}

輸出:

After changing name of t1:Sonoo Jaiswal
running...
running...
After changing name of t2:javatpoint






相關用法


注:本文由純淨天空篩選整理自 Java Thread setName() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。