java Thread构造器分析

//从这里开始,调用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的类加载器,这也是打破双亲委派模型的后门
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值