Java Thread getId()方法

2019-10-16 22:24:26

getId()方法用於返回執行緒識別符號。執行緒ID是在建立執行緒時生成的唯一正數值。

執行緒ID在其生命週期內保持不變。執行緒終止時,可以重用執行緒的ID。

語法

public long getId()

返回值

此方法返回執行緒的ID。

範例

public class GetIdExample extends Thread  
{    
    public void run()  
    {    
        System.out.println("running...");    
    }    
    public static void main(String args[])  
    {    
        // creating one thread  
        GetIdExample t1=new GetIdExample();    
        // Returns the identifier of this Thread  
        System.out.println("Name of t1: "+t1.getName());  
        System.out.println("Id of t1: "+t1.getId());   
        // Start the thread   
        t1.start();  
    }    
}

執行上面範例程式碼,得到以下結果:

Name of t1: Thread-0
Id of t1: 39
running...