Java ThreadGroup parentOf()方法

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

上一篇: Java線程組 下一篇: Java關閉掛鉤(shutdown hook)