java线程类的源码分析阅读技巧;

首先阅读thread类重点关注一下几个问题;

1、start() ,启动一个线程是如何实现的?

2、java线程状态机的变化过程以及如何实现的?

3、


1、start方法的源码如下:

new Thread(Runnable);代码内部实际代码如下:

  1. /**
  2. * Initializes a Thread.
  3. *
  4. * @param g the Thread group
  5. * @param target the object whose run() method gets called
  6. * @param name the name of the new Thread
  7. * @param stackSize the desired stack size for the new thread, or
  8. * zero to indicate that this parameter is to be ignored.
  9. * @param acc the AccessControlContext to inherit, or
  10. * AccessController.getContext() if null
  11. * @param inheritThreadLocals if {@code true}, inherit initial values for
  12. * inheritable thread-locals from the constructing thread
  13. */
  14. private void init(ThreadGroup g, Runnable target, String name,
  15. long stackSize, AccessControlContext acc,
  16. boolean inheritThreadLocals) {
  17. if (name == null) {
  18. throw new NullPointerException("name cannot be null");
  19. }
  20.  
  21. this.name = name;
  22.  
  23. Thread parent = currentThread();
  24. SecurityManager security = System.getSecurityManager();
  25. if (g == null) {
  26. /* Determine if it's an applet or not */
  27.  
  28. /* If there is a security manager, ask the security manager
  29. what to do. */
  30. if (security != null) {
  31. g = security.getThreadGroup();
  32. }
  33.  
  34. /* If the security doesn't have a strong opinion of the matter
  35. use the parent thread group. */
  36. if (g == null) {
  37. g = parent.getThreadGroup();
  38. }
  39. }
  40.  
  41. /* checkAccess regardless of whether or not threadgroup is
  42. explicitly passed in. */
  43. g.checkAccess();
  44.  
  45. /*
  46. * Do we have the required permissions?
  47. */
  48. if (security != null) {
  49. if (isCCLOverridden(getClass())) {
  50. security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
  51. }
  52. }
  53.  
  54. g.addUnstarted();
  55.  
  56. this.group = g;
  57. this.daemon = parent.isDaemon();
  58. this.priority = parent.getPriority();
  59. if (security == null || isCCLOverridden(parent.getClass()))
  60. this.contextClassLoader = parent.getContextClassLoader();
  61. else
  62. this.contextClassLoader = parent.contextClassLoader;
  63. this.inheritedAccessControlContext =
  64. acc != null ? acc : AccessController.getContext();
  65. this.target = target;
  66. setPriority(priority);
  67. if (inheritThreadLocals && parent.inheritableThreadLocals != null)
  68. this.inheritableThreadLocals =
  69. ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
  70. /* Stash the specified stack size in case the VM cares */
  71. this.stackSize = stackSize;
  72.  
  73. /* Set thread ID */
  74. tid = nextThreadID();
  75. }

然后看start方法代码如下:

  1. /**
  2. * Causes this thread to begin execution; the Java Virtual Machine
  3. * calls the <code>run</code> method of this thread.
  4. * <p>
  5. * The result is that two threads are running concurrently: the
  6. * current thread (which returns from the call to the
  7. * <code>start</code> method) and the other thread (which executes its
  8. * <code>run</code> method).
  9. * <p>
  10. * It is never legal to start a thread more than once.
  11. * In particular, a thread may not be restarted once it has completed
  12. * execution.
  13. *
  14. * @exception IllegalThreadStateException if the thread was already
  15. * started.
  16. * @see #run()
  17. * @see #stop()
  18. */
  19. public synchronized void start() {
  20. /**
  21. * This method is not invoked for the main method thread or "system"
  22. * group threads created/set up by the VM. Any new functionality added
  23. * to this method in the future may have to also be added to the VM.
  24. *
  25. * A zero status value corresponds to state "NEW".
  26. */
  27. if (threadStatus != 0)
  28. throw new IllegalThreadStateException();
  29.  
  30. /* Notify the group that this thread is about to be started
  31. * so that it can be added to the group's list of threads
  32. * and the group's unstarted count can be decremented. */
  33. group.add(this);
  34.  
  35. boolean started = false;
  36. try {
  37. start0();
  38. started = true;
  39. } finally {
  40. try {
  41. if (!started) {
  42. group.threadStartFailed(this);
  43. }
  44. } catch (Throwable ignore) {
  45. /* do nothing. If start0 threw a Throwable then
  46. it will be passed up the call stack */
  47. }
  48. }
  49. }
  50.  
  51. private native void start0();

由此可见start方法的本质是调用本地方法start0()即进行的系统调用;

2、java线程的状态机的变化情况:重点关注 Thread中的一个静态枚举内部类,State  和Thread中的一个变量 threadStatus 的变化

threadStatus代码如下:

  1. /* Java thread status for tools,
  2. * initialized to indicate thread 'not yet started'
  3. */
  4.  
  5. private volatile int threadStatus = 0;

但是奇怪的是发现在Thread类中并没有对threadStatus进行过赋值。故猜测原因是在native方法中对threadStatus进行赋值。因为该变量由volatile修饰,因此在native方法进行变量修改的同时Thread类中就能同时获取到该变量的最新值。

 
一下是完整的状态变化过程与状态代码
  1. /**
  2. * A thread state. A thread can be in one of the following states:
  3. * <ul>
  4. * <li>{@link #NEW}<br>
  5. * A thread that has not yet started is in this state.
  6. * </li>
  7. * <li>{@link #RUNNABLE}<br>
  8. * A thread executing in the Java virtual machine is in this state.
  9. * </li>
  10. * <li>{@link #BLOCKED}<br>
  11. * A thread that is blocked waiting for a monitor lock
  12. * is in this state.
  13. * </li>
  14. * <li>{@link #WAITING}<br>
  15. * A thread that is waiting indefinitely for another thread to
  16. * perform a particular action is in this state.
  17. * </li>
  18. * <li>{@link #TIMED_WAITING}<br>
  19. * A thread that is waiting for another thread to perform an action
  20. * for up to a specified waiting time is in this state.
  21. * </li>
  22. * <li>{@link #TERMINATED}<br>
  23. * A thread that has exited is in this state.
  24. * </li>
  25. * </ul>
  26. *
  27. * <p>
  28. * A thread can be in only one state at a given point in time.
  29. * These states are virtual machine states which do not reflect
  30. * any operating system thread states.
  31. *
  32. * @since 1.5
  33. * @see #getState
  34. */
  35. public enum State {
  36. /**
  37. * Thread state for a thread which has not yet started.
  38. */
  39. NEW,
  40.  
  41. /**
  42. * Thread state for a runnable thread. A thread in the runnable
  43. * state is executing in the Java virtual machine but it may
  44. * be waiting for other resources from the operating system
  45. * such as processor.
  46. */
  47. RUNNABLE,
  48.  
  49. /**
  50. * Thread state for a thread blocked waiting for a monitor lock.
  51. * A thread in the blocked state is waiting for a monitor lock
  52. * to enter a synchronized block/method or
  53. * reenter a synchronized block/method after calling
  54. * {@link Object#wait() Object.wait}.
  55. */
  56. BLOCKED,
  57.  
  58. /**
  59. * Thread state for a waiting thread.
  60. * A thread is in the waiting state due to calling one of the
  61. * following methods:
  62. * <ul>
  63. * <li>{@link Object#wait() Object.wait} with no timeout</li>
  64. * <li>{@link #join() Thread.join} with no timeout</li>
  65. * <li>{@link LockSupport#park() LockSupport.park}</li>
  66. * </ul>
  67. *
  68. * <p>A thread in the waiting state is waiting for another thread to
  69. * perform a particular action.
  70. *
  71. * For example, a thread that has called <tt>Object.wait()</tt>
  72. * on an object is waiting for another thread to call
  73. * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
  74. * that object. A thread that has called <tt>Thread.join()</tt>
  75. * is waiting for a specified thread to terminate.
  76. */
  77. WAITING,
  78.  
  79. /**
  80. * Thread state for a waiting thread with a specified waiting time.
  81. * A thread is in the timed waiting state due to calling one of
  82. * the following methods with a specified positive waiting time:
  83. * <ul>
  84. * <li>{@link #sleep Thread.sleep}</li>
  85. * <li>{@link Object#wait(long) Object.wait} with timeout</li>
  86. * <li>{@link #join(long) Thread.join} with timeout</li>
  87. * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
  88. * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
  89. * </ul>
  90. */
  91. TIMED_WAITING,
  92.  
  93. /**
  94. * Thread state for a terminated thread.
  95. * The thread has completed execution.
  96. */
  97. TERMINATED;
  98. }
  99.  
  100. /**
  101. * Returns the state of this thread.
  102. * This method is designed for use in monitoring of the system state,
  103. * not for synchronization control.
  104. *
  105. * @return this thread's state.
  106. * @since 1.5
  107. */
  108. public State getState() {
  109. // get current thread state
  110. return sun.misc.VM.toThreadState(threadStatus);
  111. }

java Thread 类的源码阅读(oracle jdk1.8)的更多相关文章

  1. Java多线程类FutureTask源码阅读以及浅析

    FutureTask是一个具体的实现类,实现了RunnableFuture接口,RunnableFuture分别继承了Runnable和Future接口,因此FutureTask类既可以被线程执行,又 ...

  2. 《java.util.concurrent 包源码阅读》13 线程池系列之ThreadPoolExecutor 第三部分

    这一部分来说说线程池如何进行状态控制,即线程池的开启和关闭. 先来说说线程池的开启,这部分来看ThreadPoolExecutor构造方法: public ThreadPoolExecutor(int ...

  3. 25 BasicUsageEnvironment0基本使用环境基类——Live555源码阅读(三)UsageEnvironment

    25 BasicUsageEnvironment0基本使用环境基类——Live555源码阅读(三)UsageEnvironment 25 BasicUsageEnvironment0基本使用环境基类— ...

  4. 24 UsageEnvironment使用环境抽象基类——Live555源码阅读(三)UsageEnvironment

    24 UsageEnvironment使用环境抽象基类——Live555源码阅读(三)UsageEnvironment 24 UsageEnvironment使用环境抽象基类——Live555源码阅读 ...

  5. 12 哈希表相关类——Live555源码阅读(一)基本组件类

    12 哈希表相关类--Live555源码阅读(一)基本组件类 这是Live555源码阅读的第一部分,包括了时间类,延时队列类,处理程序描述类,哈希表类这四个大类. 本文由乌合之众 lym瞎编,欢迎转载 ...

  6. 《java.util.concurrent 包源码阅读》 结束语

    <java.util.concurrent 包源码阅读>系列文章已经全部写完了.开始的几篇文章是根据自己的读书笔记整理出来的(当时只阅读了部分的源代码),后面的大部分都是一边读源代码,一边 ...

  7. 18 TaskScheduler任务调度器抽象基类——Live555源码阅读(一)任务调度相关类

    这是Live555源码阅读的第二部分,包括了任务调度相关的三个类.任务调度是Live555源码中很重要的部分. 本文由乌合之众 lym瞎编,欢迎转载 http://www.cnblogs.com/ol ...

  8. 13 HashTable抽象哈希表类——Live555源码阅读(一)基本组件类

    这是Live555源码阅读的第一部分,包括了时间类,延时队列类,处理程序描述类,哈希表类这四个大类. 本文由乌合之众 lym瞎编,欢迎转载 http://www.cnblogs.com/oloroso ...

  9. 11 AlarmHandler定时处理类——Live555源码阅读(一)基本组件类

    这是Live555源码阅读的第一部分,包括了时间类,延时队列类,处理程序描述类,哈希表类这四个大类. 本文由乌合之众 lym瞎编,欢迎转载 http://www.cnblogs.com/oloroso ...

随机推荐

  1. 芯灵思Sinlinx A64 linux 通过设备树写LED驱动(附参考代码,未测试)

    开发平台 芯灵思Sinlinx A64 内存: 1GB 存储: 4GB 详细参数 https://m.tb.cn/h.3wMaSKm 开发板交流群 641395230 全志A64设备树结构体 #inc ...

  2. JIT(Just in time,即时编译,边运行边编译)、AOT(Ahead Of Time,运行前编译),是两种程序的编译方式

    JIT(Just in time,即时编译,边运行边编译).AOT(Ahead Of Time,运行前编译),是两种程序的编译方式

  3. 剑指offer 9.递归和循环 变态跳台阶

    题目描述 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级.求该青蛙跳上一个n级的台阶总共有多少种跳法.   这道题还是编程题?   数学渣渣看到心拔凉拔凉的,   要用到数学归纳法来 ...

  4. upstream timed out (10060: A connection attempt failed because the connected party did not properly respond

    openresty 错误日志报错内容: // :: [error] #: * upstream timed : A connection attempt failed because the conn ...

  5. Xshell5 提示要继续使用此程序,您必须应用最新的更新或使用新版本

    Xshell5 提示要继续使用此程序,您必须应用最新的更新或使用新版本   目录 问题描述 修改系统时间 安装新版本 下载 安装 回到顶部 问题描述 今天上线一个服务,上完准备看下OPS的发布结果,就 ...

  6. elasticSearch 2.3 delete-by-query plugin

    The delete-by-query plugin adds support for deleteing all of the documents which match the specified ...

  7. YARN简述

    YARN(Yet Another Resource Negotiator)是Hadoop的集群资源管理系统.YARN提供请求和使用集群资源的API,但这些API很少直接用于用户代码.相反,用户代码中用 ...

  8. Lubuntu下小巧好用的Python编辑工具Geany

    在Lubuntu系统上有很多的Python编辑器,如eclipse,PyCharm等,功能繁多,市场占有率高,但动辄几百M的体积有些巨大,博主今天推荐一款精简且易用的Python开发工具--Geany ...

  9. Cleanmymac X好不好用?

    Cleanmymac X是一款Mac清理软件,能够帮助我们快速实现快速实现磁盘清理,是mac用户的智能助手.那么为什么大家会认定它并坚定不移呢?小编带你感受感受. 1. 简洁大气的外观. 用户正版官方 ...

  10. catkin-make: command not found 错误解决

    参考网址:https://answers.ros.org/question/212492/catkin_make-command-not-found/ zc@ubuntu:~ $ source /op ...