Java Thread getThreadGroup()方法

2019-10-16 22:24:48

Thread類的getThreadGroup()方法用於返回該執行緒所屬的執行緒的執行緒組。 如果此執行緒已死(已停止),則此方法返回null

語法

public final ThreadGroup getThreadGroup()

返回
此方法返回執行緒的執行緒組。

範例

class JavaGetThreadGroupExp implements Runnable {  
    public void run()   
    {  
        System.out.println("tw511.com");  
    }  
}  
public class GetThreadGroup   
{  
    public static void main(String[] args)   
    {  
        // create thread groups  
        ThreadGroup group = new ThreadGroup("ThreadGroup");  
        ThreadGroup anotherGroup = new ThreadGroup(group, "AnotherGroup");  

        // create threads and placed into thread group  
        Thread t1 = new Thread(group, new JavaGetThreadGroupExp(), "Thread-1");  
        Thread t2 = new Thread(anotherGroup, new JavaGetThreadGroupExp(), "Thread-2");  

        // Start the threads  
        t1.start();  
        t2.start();  

        // returns the Thread Group to which this thread belongs  
        System.out.println(t1.getName() +" is a member of " + t1.getThreadGroup().getName());  
        System.out.println(t2.getName()+ " is a member of "+ t2.getThreadGroup().getName());  
    }  
}

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

Thread-1 is a member of ThreadGroup
Thread-2 is a member of AnotherGroup
tw511.com
tw511.com

上面的範例使用Thread類的getThreadGroup()方法獲取ThreadGroup的物件,然後使用getName()方法獲取執行緒組的名稱。