Java ThreadGroup parentOf()方法

2019-10-16 22:24:07

ThreadGroup類的parentOf()方法測試執行緒組是執行緒組的引數還是其祖先執行緒組之一。

語法

public final boolean parentOf(ThreadGroup g)

引數

  • g:它是一個執行緒組

返回

如果呼叫執行緒是組的父級,則返回true。 否則,它返回false

範例

class NewThread extends Thread   
{  
    NewThread(String threadname, ThreadGroup tg)  
    {  
        super(tg, threadname);  
    }  
public void run()  
    {  
        for (int i = 0; i < 5; i++)   
        {  
            try  
            {  
                Thread.sleep(10);  
            }  
            catch (InterruptedException ex){  
            }  
        }  
        System.out.println(Thread.currentThread().getName() + " completed executing");  
    }  
}   
public class ThreadGroupParentOfExp   
{  
    public static void main(String arg[]) throws InterruptedException,  
        SecurityException, Exception  
    {  
        // creating the thread group  
        ThreadGroup g1 = new ThreadGroup("Parent thread");  
        ThreadGroup g2 = new ThreadGroup(g1, "Child thread");  

        // creating a thread   
        NewThread t1 = new NewThread("Thread-1", g1);  
        System.out.println(t1.getName()+" starts");  
        t1.start();  

        // creating another thread   
        NewThread t2 = new NewThread("Thread-2", g1);  
        System.out.println(t2.getName()+" starts");  
        t2.start();  

        // checking who is parent thread  
        boolean isParent = g2.parentOf(g1);  
        System.out.println(g2.getName() + " is the parent of " + g1.getName() +": "+ isParent);  

        isParent = g1.parentOf(g2);  
        System.out.println(g1.getName() + " is the parent of " + g2.getName() +": "+ isParent);  
    }  
}

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

Thread-1 starts
Thread-2 starts
Child thread is the parent of Parent thread: false
Parent thread is the parent of Child thread: true
Thread-1 completed executing
Thread-2 completed executing