在Thread的构造函数中,可以显式地指定线程的Group,也就是ThreadGroup。接着下面介绍Thread init方法的源码:
SecurityManager security=System.getSecurityManager();if(g==null){
/*Determine if it's an applet or not*/
/*If there is a security manager,ask the security man:what to do.*/
if(security!=null){
g=security.getThreadGroup();
/*If the security doesn't have a strong opinion of the use the parent thread group.*/
if(g==null){
g=parent.getThreadGroup();
}
}
通过对源码进行分析,我们可以看出,如果在构造Thread的时候没有显示地指定一个ThreadGroup,那么子线程将会被加入父线程所在的线程组,下面写一个简单的代码来测试一下,如下所示:
ThreadConstruction.java package com.wangwenjun.concurrent.chapter02;
public class ThreadConstruction
{
public static void main(String[]args)
//①
Thread t1=new Thread("t1");
1/②
ThreadGroup group=new ThreadGroup("TestGroup");
1/③
Thread t2=new Thread(group,"t2");
ThreadGroup mainThreadGroup=Thread.currentThread()
System.out.println("Main thread belong group:"+ma;
System.out.println("tl and main belong the same grot ;
System.out.println("t2 thread group not belong main ;
System.out.println("t2 thread group belong main Test;
}
}
在默认设置中,当然除了子线程会和父线程同属于一个Group之外,它还会和父线程拥有同样的优先级。以上就是Java编程在Thread构造函数中,编写Thread init方法源码的编程。