1 /** 2 * Initializes a Thread. 3 * 初始化一个线程 4 * @param g the Thread group 线程组 5 run()方法被调用的对象 6 * @param target the object whose run() method gets called 7 * @param name the name of the new Thread 线程名称 8 新线程所需栈的深度,给0值表示忽略此参数 9 * @param stackSize the desired stack size for the new thread, or 10 * zero to indicate that this parameter is to be ignored. 11 * @param acc the AccessControlContext to inherit, or 12 * AccessController.getContext() if null 13 是否从构造线程继承thread-locals 14 * @param inheritThreadLocals if {@code true}, inherit initial values for 15 * inheritable thread-locals from the constructing thread 16 */ 17 private void init(ThreadGroup g, Runnable target, String name, 18 long stackSize, AccessControlContext acc, 19 boolean inheritThreadLocals) { 20 if (name == null) { 21 throw new NullPointerException("name cannot be null"); 22 } 23 24 this.name = name; 25 父线程是当前线程 26 Thread parent = currentThread(); 27 SecurityManager security = System.getSecurityManager(); 28 if (g == null) { 29 /* Determine if it's an applet or not */ 30 31 获取安全管理器的线程组 32 /* If there is a security manager, ask the security manager 33 what to do. */ 34 if (security != null) { 35 g = security.getThreadGroup(); 36 } 37 38 获取父线程的线程组 39 /* If the security doesn't have a strong opinion of the matter 40 use the parent thread group. */ 41 if (g == null) { 42 g = parent.getThreadGroup(); 43 } 44 } 45 46 /* checkAccess regardless of whether or not threadgroup is 47 explicitly passed in. */ 48 g.checkAccess(); 49 50 /* 51 * Do we have the required permissions? 52 */ 53 if (security != null) { 54 if (isCCLOverridden(getClass())) { 55 security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION); 56 } 57 } 58 59 增加线程组中未启动线程的计数。 60 未启动的线程不会添加到线程组中,以便在从未启动时可以收集它们,但必须对它们进行计数,以便不破坏其中包含未启动线程的守护进程线程组。 61 g.addUnstarted(); 62 63 this.group = g; 64 新线程是否是守护线程取决于父类 65 this.daemon = parent.isDaemon(); 66 优先级默认为父线程的优先级 67 this.priority = parent.getPriority(); 68 if (security == null || isCCLOverridden(parent.getClass())) 69 this.contextClassLoader = parent.getContextClassLoader(); 70 else 71 this.contextClassLoader = parent.contextClassLoader; 72 this.inheritedAccessControlContext = 73 acc != null ? acc : AccessController.getContext(); 74 this.target = target; 75 setPriority(priority); 76 如果要继承父类的ThreadLocal,且父类的ThreadLocal不为空 77 if (inheritThreadLocals && parent.inheritableThreadLocals != null) 78 this.inheritableThreadLocals = 79 ThreadLocal.createInheritedMap(parent.inheritableThreadLocals); 80 /* Stash the specified stack size in case the VM cares */ 81 this.stackSize = stackSize; 82 生成线程id 83 /* Set thread ID */ 84 tid = nextThreadID(); 85 }
初始化线程的核心方法
参数:ThreadGroup(线程组) Runnable