当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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 ThreadGroup parentOf() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。