privateThread(ThreadGroup g, Runnable target, String name, long stackSize, AccessControlContext acc, boolean inheritThreadLocals) { // 参数校验 if (name == null) { thrownewNullPointerException("name cannot be null"); } this.name = name; // 获取父线程 Threadparent= currentThread(); SecurityManagersecurity= System.getSecurityManager(); if (g == 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 manager doesn't have a strong opinion on 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( SecurityConstants.SUBCLASS_IMPLEMENTATION_PERMISSION); } }
g.addUnstarted();
this.group = g; // daemon和优先级继承自父线程 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); // 机场parent的threadLocal 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 */ this.tid = nextThreadID(); }
构造函数只完成了参数的配置
静态工具方法
获取当前线程
1
public static native Thread currentThread();
查找方法表
断点
jvm在运行时会记录当前的thread
使用时即可直接返回
线程让位
A hint to the scheduler that the current thread is willing to yield its current use of a processor
向调度器表示出让当前线程的时间片
1
publicstaticnativevoidyield();
通过系统调用出让cpu执行时间片
线程休眠
使得线程进入休眠
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicstaticvoidsleep(long millis, int nanos) throws InterruptedException { if (millis < 0) { thrownewIllegalArgumentException("timeout value is negative"); }
if (nanos < 0 || nanos > 999999) { thrownewIllegalArgumentException( "nanosecond timeout value out of range"); } // 四舍五入 if (nanos >= 500000 || (nanos != 0 && millis == 0)) { millis++; } // sleep sleep(millis); }
publicintactiveCount() { int result; // Snapshot sub-group data so we don't hold this lock // while our children are computing. int ngroupsSnapshot; ThreadGroup[] groupsSnapshot; synchronized (this) { if (destroyed) { return0; } // 当前组线程数 result = nthreads; // 子group ngroupsSnapshot = ngroups; if (groups != null) { groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot); } else { groupsSnapshot = null; } } // 遍历每一个group返回count累加和 for (inti=0 ; i < ngroupsSnapshot ; i++) { result += groupsSnapshot[i].activeCount(); } return result; }
// Get a snapshot of the list of all threads // 获取所有线程 Thread[] threads = getThreads(); // 获取堆栈信息 StackTraceElement[][] traces = dumpThreads(threads); Map<Thread, StackTraceElement[]> m = newHashMap<>(threads.length); for (inti=0; i < threads.length; i++) { StackTraceElement[] stackTrace = traces[i]; if (stackTrace != null) { m.put(threads[i], stackTrace); } // else terminated so we don't put it in the map } return m; }
publicsynchronizedvoidstart() { /** * This method is not invoked for the main method thread or "system" * group threads created/set up by the VM. Any new functionality added * to this method in the future may have to also be added to the VM. * * A zero status value corresponds to state "NEW". */ if (threadStatus != 0) thrownewIllegalThreadStateException();
/* Notify the group that this thread is about to be started * so that it can be added to the group's list of threads * and the group's unstarted count can be decremented. */ // 添加到线程组 group.add(this);
booleanstarted=false; try { // jni start0(); started = true; } finally { // 判断是否正常开启 try { if (!started) { group.threadStartFailed(this); } } catch (Throwable ignore) { /* do nothing. If start0 threw a Throwable then it will be passed up the call stack */ } } }
publicfinalvoidstop() { SecurityManagersecurity= System.getSecurityManager(); // 权限鉴别 if (security != null) { checkAccess(); if (this != Thread.currentThread()) { security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION); } } // A zero status value corresponds to "NEW", it can't change to // not-NEW because we hold the lock. // 如果进程已经start if (threadStatus != 0) { // 如果处于挂起状态唤醒线程 resume(); // Wake up thread if it was suspended; no-op otherwise }
// The VM can handle all thread states stop0(newThreadDeath()); }
发送消息入队列
打断
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
publicvoidinterrupt() { if (this != Thread.currentThread()) { checkAccess();
// thread may be blocked in an I/O operation // 可能由于io而等待 synchronized (blockerLock) { Interruptibleb= blocker; if (b != null) { // 打断 interrupt0(); // set interrupt status b.interrupt(this); return; } } }