//从这里开始,调用init方法
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
//g线程组 target任务 name线程名称 stackSize线程栈大小
private void init(ThreadGroup g, Runnable target, String name,long stackSize) {
init(g, target, name, stackSize, null, true);
}
//
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;
//当前线程即就是 parent线程(当前线程由另一个线程创建)
Thread parent = currentThread();
SecurityManager security = System.getSecurityManager();
if (g == null) {
if (security != null) {
//创建线程所在线程组
g = security.getThreadGroup();
}
//与parent线程组相同
if (g == null) {
g = parent.getThreadGroup();
}
}
//线程组检查权限
g.checkAccess();
//安全检查
if (security != null) {
if (isCCLOverridden(getClass())) {
security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
}
}
//计数
g.addUnstarted();
//当前线程组
this.group = g;
//和parent是否守护线程同步
this.daemon = parent.isDaemon();
//优先级
this.priority = parent.getPriority();
if (security == null || isCCLOverridden(parent.getClass()))
//类加载器同parent
this.contextClassLoader = parent.getContextClassLoader();
else
//类加载器同parent
this.contextClassLoader = parent.contextClassLoader;
//设置inheritedAccessControlContext
this.inheritedAccessControlContext =
acc != null ? acc : AccessController.getContext();
//执行目标(task)
this.target = target;
//设置优先级
setPriority(priority);
if (inheritThreadLocals && parent.inheritableThreadLocals != null)
//来自parent
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
//线程栈大小
this.stackSize = stackSize;
//线程id,虚拟机分配
tid = nextThreadID();
}
总结:每个线程的类加载器默认来着与parent的类加载器,这也是打破双亲委派模型的后门
java Thread构造器分析
最新推荐文章于 2023-04-03 20:04:41 发布