Java Thread currentThread()方法

2019-10-16 22:24:18

Thread類的currentThread()方法用於返回對當前正在執行的執行緒物件的參照。

public static Thread currentThread()

返回值
它返回當前正在執行的執行緒。

範例

public class CurrentThreadExp extends Thread  
{    
    public void run()  
    {    
        // print currently executing thread   
        System.out.println(Thread.currentThread().getName());    
    }    
    public static void main(String args[])  
    {    
        // creating two thread  
        CurrentThreadExp t1=new CurrentThreadExp();    
        CurrentThreadExp t2=new CurrentThreadExp();    
        // this will call the run() method  
        t1.start();    
        t2.start();    
    }    
}

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

Thread-0
Thread-1