Java教程

Java线程组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

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4