1、构造器
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
点击nextThreadNum进入步骤2。
点击init进入步骤3。
2、nextThreadNum方法
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}
不指定线程名称时,默认会自动生成:Thread-0,Thread-1。。。加了synchronized,能保证每个线程的名称能按顺序增长。
3、init方法
private void init(ThreadGroup g, Runnable target, String name,
long stackSize) {
init(g, target, name, stackSize, null, true);
}
4、init方法
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc,
boolean inheritThreadLocals) {
if (name == null) {
throw new NullPointerException("name cannot be null");
}
this.name = name;
Thread parent = currentThread();
SecurityManager security = System.getSecurityManager();
if (g == null) { //threadGroup为null
/* Determine if it's an applet or not */
/* If there is a security manager, ask the security manager
what to do. */
if (security != null) {
g = security.getThreadGroup();
}
/* If the security doesn't have a strong opinion of the matter
use the parent thread group. */
if (g == null) {
//如果没有指定线程组,默认就是父线程的线程组
g = parent.getThreadGroup();
}
}
/* checkAccess regardless of whether or not threadgroup is
explicitly passed in. */
g.checkAccess();
/*
* Do we have the required permissions?
*/
if (security != null) {
if (isCCLOverridden(getClass())) {
security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
}
}
g.addUnstarted();
this.group = g; //设置线程组
this.daemon = parent.isDaemon();
this.priority = parent.getPriority();
if (security == null || isCCLOverridden(parent.getClass()))
this.contextClassLoader = parent.getContextClassLoader();
else
this.contextClassLoader = parent.contextClassLoader;
this.inheritedAccessControlContext =
acc != null ? acc : AccessController.getContext();
this.target = target;
setPriority(priority);
if (inheritThreadLocals && parent.inheritableThreadLocals != null)
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
/* Stash the specified stack size in case the VM cares */
this.stackSize = stackSize;
/* Set thread ID */
tid = nextThreadID();
}
分析:
1)如果name为null,则抛出异常
if (name == null) {
throw new NullPointerException("name cannot be null");
}
2)创建线程时,获取到的currentThread()是当前创建你的那个线程,比如main线程在创建线程A,在这个过程中,获取到的currentThread()就是main线程
Thread parent = currentThread();
3) 每个线程必须属于一个ThreadGroup,如果不指定threadGroup,那么默认就是父线程的线程组
if (g == null) { //threadGroup为null
if (security != null) {
g = security.getThreadGroup();
}
if (g == null) {
//如果没有指定线程组,默认就是父线程的线程组
g = parent.getThreadGroup();
}
}
4)如果没有指定是否为daemon,那么daemon的状态是由父线程决定的。即,如果你的父线程是daemon线程,那么你也是daemon线程。
this.daemon = parent.isDaemon();
5)优先级如果没有指定,那么就跟父线程的优先级保持一致
this.priority = parent.getPriority();
6)每个线程都有个ThreadID的概念,从1开始递增。
tid = nextThreadID();
5、总结
1)创建你的线程,就是你的父线程
2)默认的ThreadGroup就是父线程的ThreadGroup
3)默认的daemon状态是父线程的daemon状态
4)默认的优先级是父线程的优先级
5)默认的线程名称是Thread-X的形式
6)线程id是从1开始的全局递增。