并发番@Thread一文通(1.7版)

904 阅读37分钟
原文链接: www.zybuluo.com
  • 本文的运行环境如下(笔者家用主机配置):
    image_1bnbi6ith1db41gfnmjn17jv1rbk2t.png-4.5kB

1.什么是线程

1.1 线程的概述

  • 一个运行程序就是一个进程,而线程是进程中独立运行的子任务
  • 线程是操作系统执行流中的最小单位,一个进程可以有多个线程,这些线程与该进程共享同一个内存空间
  • 线程是系统独立调度和分派CPU的基本单位,通常有就绪运行阻塞三种基本状态
  • 随着硬件水平的提高,多线程能使系统的运行效率得到大幅度的提高,同时异步操作也增加复杂度和各种并发问题

1.2 线程相关的重要概念

  • 同步(Synchronous) VS 异步(Asynchronous)
  • 同步:同步方法一旦开始,调用者必须等到方法调用返回之后,才能继续后续行为
  • 异步:异步方法调用更像一个消息传递,一旦开始,方法调用便立即返回,调用者就可以继续后续行为;异步方法通常会由另一个线程执行;若异步调用需要返回结果时,当异步调用完成后,需要通知调用者
  • 并发(Synchronous) VS 并行(Asynchronous)
  • 并发:并发的多个任务可能是交替执行,系统会不停地在两者间切换,一会执行任务1,一会执行任务2
  • 并行:并行的多个任务是真实的同时执行,真实的并行只可能出现在多核CPU环境下(由于一个CPU一次只能执行一条指令,单核情况下多线程就是并发)
  • 临界区(Critical Zone)
  • 临界区: 一般指的是公共共享资源,即可以被多个线程共享使用。但同一时间只能由一个线程去访问和操作临界区的资源,一旦临界区资源被一个线程占用,其他线程也想要使用该资源就必须等待,就好比好多人想上大号,但只有一个坑,一个人占了坑,其他人就得排队等待喽
  • 阻塞(Critical Zone) vs 非阻塞(Critical Zone)
  • 阻塞:当一个线程占用临界区资源,其他线程也想要使用该资源就必须等待,等待会导致线程的挂起,也就是阻塞(线程变成阻塞状态)。此时若占用资源的线程一直不愿意释放资源,那么其他所有阻塞在该临界区的线程都会被挂起,变成阻塞状态,不能正常工作,直到占用线程释放资源
  • 非阻塞:非阻塞强调没有一个线程可以妨碍其他线程执行,所有线程都会尝试去做下一步工作
  • 注意与"同异"不是一回事,"同异"注重的是通信机制相关的方法返回处理,阻塞注重的是线程间对于临界区资源竞争的影响

1.3 多线程的风险

  • 上下文切换
  • 上下文切换: CPU通过时间片分配算法来循环执行任务,当前任务执行一个时间片后会切换到下一个任务。但是,在切换前会保存上一个任务的状态,以便下次切换回这个任务时可以重新加载这个任务的状态。所有任务从保存到再加载的过程就是一次上下文切换
  • 多线程性能问题:由于线程有创建和上下文切换的开销,在多线程环境下,这种开销对时间和资源的利用都是一个极大的负担,很可能导致并发任务执行速度还不如串行快
  • 减少上下文切换: 无锁并发编程、CAS算法、减少并发、使用最少线程、协程
    • 无锁并发编程:避免使用锁,比如数据分段执行(MapReduce)、尽可能使用无状态对象、避免竞争情况等
    • CAS算法:java.util.concurrent包中大量使用CAS算法,比如AtomicAQS
    • 减少并发:JAVA8中新引入的LongAdderDoubleAdder等新类,将CAS算法替换成value分担原则
    • 使用最少线程:避免创建不必要的线程,当任务很少但线程很多时,会导致大量线程为等待状态
    • 协程:在单线程里实现多任务的调度,并在单线程里维持多个任务间的切换
  • 竞争条件
  • 竞争条件指多个线程并发访问和操作同一数据且执行结果与线程访问的特定顺序有关
  • 竞争条件发生在当多个线程在读写数据时,其最终的的结果依赖于多个线程指令执行顺序
  • 由于竞争条件的指令顺序操作的不确定性甚至是错误的,可能会造成结果的混乱,例如臭名昭著的i++的原子性问题
  • 活跃性失败问题
  • 饥饿(Starvation): 饥饿是指某一个或多个线程因为种种原因无法获得所需要的资源,导致一直无法执行,如:
    • 比如该线程的优先级比较低,而高优先级的线程不断抢占它的资源,导致低优先级线程一直无法正常工作
    • 比如某个线程长时间占用关键资源不释放,导致其他线程不可用(区别于死锁,任务执行完毕还是会释放的)
  • 活锁(Livelock): 活锁比较有趣,线程们都是懂得谦让的君子,会主动释放资源,结果就是资源不断在两个线程中跳动,而没有一个线程可以同时拿到所有资源而正常执行(比如yield方法
  • 死锁(Deadlock): 线程间相互等待对方释放锁而形成死循环,即产生死锁,从而造成系统功能不可用:比如线程拿到锁之后,因为一些异常没有释放锁,或是线程在释放锁的时候出现异常,没有成功释放;这时候由于服务不能继续使用了,所有只能通过dump线程查看到底是哪个线程出现了问题。
  • 避免死锁的几个常见方法:
    • 避免一个线程同时获取多个锁
    • 避免一个线程在锁内同时占用多个资源,尽量保证每个锁只占用一个资源
    • 尝试使用定时锁,使用lock.tryLock(timewout)来替代使用内部锁机制
    • 对于数据库锁,加锁和解锁必须在一个数据库连接离,否则会出现解锁失败的情况

1.4 并发级别

  • 阻塞(Blocking)
  • 线程若是阻塞的,那么在其他线程释放资源之前,当前线程会被挂起,无法继续执行
  • 在Java中,若使用 synchronized 关键字或者重入锁时,得到的就是阻塞的线程
  • 无论是 synchronized 还是重入锁,都会试图在执行后续代码之前,竞争临界区的锁:
    • 如果竞争成功,当前线程会获得锁并占用资源,从而继续往后执行
    • 如果竞争失败,继续挂起阻塞,等待下次资源被释放后的再次竞争
  • 无饥饿(Starvation-Free)
  • 若线程间区分优先级,那么线程调度通常会优先满足高优先级的线程(非公平原则),就可能产生饥饿
  • 对于非公平的锁来说,系统允许高优先级的线程插队,这样就可能导致低优先级线程产生饥饿
  • 对于公平的锁来说,不管新到的线程优先级多高都需要乖乖排队,所有线程都有机会执行,饥饿很难产生
  • 当一个任务非常耗时导致某线程一直占据关键资源不放,其他线程难以获取,此时其他线程也可以说是饥饿的
  • 无障碍(Obstruction-Free)
  • 无障碍是最弱的非阻塞调度:当两个线程无障碍执行,那么就不会以为临界区问题导致一方被挂起,而是共享临界区
  • 此时若是一个线程对临界区共享数据进行修改操作,对于无障碍线程来说,一旦检测到这种情况,会立即对自己所做的修改进行回滚,确保数据安全(类似事务的概念)
  • 无障碍类似于乐观锁,线程在操作之前,先读取并保存一个"一致性标记",操作完成后,再次读取,检查这个标记是否被变更过,如果两者一致,说明没有冲突;否则就有冲突,会重试或者回滚(跟Git差不多,区别是Git需要手动merge或者revert)
  • 无锁(Lock-Free)
  • 无锁的并行都是无障碍。在无锁情况下,所有线程都能尝试对临界区进行访问,区别是无锁的并发保证必然有一个线程能够在有限步内完成操作并离开临界区
  • 如果线程一直尝试不成功,可能会出现饥饿的情况,这样常见于无穷循环调用
  • 笔者将在并发番@Lock一文通(排期中)中会进一步介绍锁的优化
  • 无等待(Wait-Free)
  • 无等待是在无锁的基础上拓展,它要求所有的线程都必须在有限步内完成,这样就不会有饥饿问题
  • 一个典型的无等待结构是RCU(Read-Copy-Update)。它的基本思想是:读操作都是无等待,写操作时,需要先获取原始数据副本,接着只修改副本数据,修改完后,在合适的时机回写数据
  • RCU在JAVA中应用的非常广泛,比如(JAVA的观察者模式的JDK实现)ObservablenotifyObservers()方法,ArrayListresize()方法等等

1.4 Java线程状态的转换

  • Java线程状态转换图

Java线程状态转换.jpg-581.7kB

  • Java线程状态转换
  • 新建(new):新创建一个线程对象:在JAVA中的表现就是Thread thread = new Thread()
  • 就绪(runnable):线程创建后,其他线程调用该对象的start方法。该状态的线程位于可运行线程池中,等待被线程调度选中,获取CPU时间分片使用权:在JAVA中的表现就是thread.start()
  • 运行(running):就绪态线程获取到CPU时间分片之后,就可以执行任务:在JAVA中的表现就是thread.run(),但需要注意的是,此时线程不一定是立即执行,这跟系统调度有关
  • 阻塞(block):阻塞状态是指线程因为某种原因放弃CPU使用权,让出CPU时间片,暂时停止运行(注意此时线程在内存中是存在的,并没有被GC),直到线程进入就绪态,才有机会再次获取时间片转成运行态。阻塞分三种情况:
    • 常规阻塞:运行态线程在发出I/O请求、执行Thread.sleep方法t.join方法时,JVM会将该线程设置为阻塞状态;当I/O处理完毕并发出响应sleep方法超时join等待线程终止或超时,线程重新转入就绪态
    • 同步阻塞:运行态线程在获取对象的同步锁时,当该同步锁已被其他线程占用,JVM会将该线程暂时放入同步队列中,当其他线程放弃同步锁同时该线程竞争到该同步锁时,该线程转为就绪态
    • 等待阻塞:运行态线程执行wait方法,JVM会将该线程放入等待队列中,直到被其他线程唤醒或其他线程中断超时,再次获取同步锁标识,重新进入就绪态`
  • 死亡(dead):线程main方法、run方法执行完毕或出现异常,则该线程生命周期结束。已死亡线程不可复生,当然可以使用线程池机制来提高线程的复用性,避免线程被直接杀死
  • Java线程状态枚举
  1. /**
  2. * JAVA对于线程状态的枚举类,使用jstack查看dump文件可以看到相对应的线程状态
  3. * 注意:状态的转换要以状态图为参照标准,枚举类只是用来统一记录某种状态以方便JAVA代码编写!
  4. * 对应JVM中对线程的监控的4种核心抽象状态:
  5. * 运行(running),休眠(Sleeping),等待(Wait),监视(Monitor)
  6. */
  7. public enum State {
  8. /**
  9. * Thread state for a thread which has not yet started.
  10. * 新建:线程创建但还不是就绪态(Thread还没有执行start方法)
  11. */
  12. NEW,
  13. /**
  14. * Thread state for a runnable thread. A thread in the runnable
  15. * state is executing in the Java virtual machine but it may be waiting
  16. * for other resources from the operating system such as processor.
  17. * 运行状态:Java将就绪态和运行态统一设置为RUNNABLE
  18. * 笔者认为这可能与Thread执行start方法之后会立即执行run方法有关
  19. */
  20. RUNNABLE,
  21. /**
  22. * Thread state for a thread blocked waiting for a monitor lock.
  23. * A thread in the blocked state is waiting for a monitor lock to enter
  24. * a synchronized block/method or reenter a synchronized block/method
  25. * after calling {@link Object#wait() Object.wait}.
  26. * 阻塞:线程正等待获取监视锁(同步锁),调用wait方法就会阻塞当前线程
  27. * 只有获取到锁的线程才能进入或重入同步方法或同步代码
  28. */
  29. BLOCKED,
  30. /**
  31. * Thread state for a waiting thread.
  32. * A thread is in the waiting state due to calling one of the following methods:
  33. * <ul>
  34. * <li>{@link Object#wait() Object.wait} with no timeout</li>
  35. * <li>{@link #join() Thread.join} with no timeout</li>
  36. * <li>{@link LockSupport#park() LockSupport.park}</li>
  37. * </ul>
  38. * 调用以上方法会使线程进入等待状态
  39. * <p>A thread in the waiting state is waiting for another thread to
  40. * perform a particular action.
  41. * 进入等待状态的线程,需要等待其他线程的唤醒才能继续运行
  42. * For example, a thread that has called <tt>Object.wait()</tt>
  43. * on an object is waiting for another thread to call
  44. * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
  45. * that object. A thread that has called <tt>Thread.join()</tt>
  46. * is waiting for a specified thread to terminate.
  47. * 比如线程被wait方法执行等待,需要被notify或notifyAll唤醒
  48. * 再比如join方法会等待一个指定线程结束之后才会继续运行
  49. */
  50. WAITING,
  51. /**
  52. * Thread state for a waiting thread with a specified waiting time.
  53. * A thread is in the timed waiting state due to calling one of
  54. * the following methods with a specified positive waiting time:
  55. * <ul>
  56. * <li>{@link #sleep Thread.sleep}</li>
  57. * <li>{@link Object#wait(long) Object.wait} with timeout</li>
  58. * <li>{@link #join(long) Thread.join} with timeout</li>
  59. * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
  60. * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
  61. * </ul>
  62. * 调用以上方法会使线程进入等待状态,但会超时返回
  63. */
  64. TIMED_WAITING,
  65. /**
  66. * Thread state for a terminated thread.
  67. * The thread has completed execution.
  68. * 终止:当线程任务完成之后,就终止了
  69. */
  70. TERMINATED;
  71. }
  • 枚举类图表如下所示:

image_1bng2kgliedt155cg1o47n1pec1e.png-92kB

  • 调用与线程有关的方法是造成线程状态改变的主要原因,枚举类的转换如下图所示:

QQ截图20170814181448.png-125.5kB

  • synchronized vs Lock
  • 阻塞状态是线程阻塞在进入同步方法或同步块(获取锁)时的状态
  • concurrent包下Lock接口的线程状态却是等待状态,因为阻塞实现是基于LockSupport类方法
  • Dump文件中的线程状态
  • 死锁:Deadlock(重点关注)
  • 等待资源:Waiting on condition(重点关注)
  • 等待获取监视器:Waiting on monitor entry(重点关注)
  • 阻塞:Blocked(重点关注)
  • 执行中:Runnable
  • 暂停:Suspended
  • 对象等待中:Object.wait() 或 TIMED_WAITING
  • 停止:Parked

致谢:Java线程Dump分析工具--jstack

2.什么是Thread

  • JAVA中实现多线程编程主要有两种:一种是继承 Thread类,另一种是实现 Runnable接口
  • Thread 是JDK对线程的抽象实现类,封装了有关线程的一些基本信息和操作
  • JVM允许一个应用有多个线程并发执行,优先级高的线程优先执行
  • JVM启动后,会创建一些守护线程来进行自身的常规管理(垃圾回收,终结处理),以及一个运行main函数的主线程
  • 当满足以下其中一个条件时,JVM将停止线程运行:
    1. Runtime执行exit()方法同时安全管理器允许该操作被执行
    2. 所有非守护线程全部死亡或run()方法返回或在执行run()方法时抛出异常并传播
  • Bruce Eckel(圣经 <<Java编程思想>> 作者)大神认为Runnable应该更为名Task,即任务,这点笔者深感赞同
  • 同时Bruce Eckel<<Java编程思想>>对于线程组的想法是:没有研究的价值,因此本文先不涉及线程组
  • 此版本基于JDK1.7

3.Thread的数据结构

3.1 类定义

  1. //Thread类
  2. public class Thread implements Runnable
  3. //Runnable接口
  4. public interface Runnable {
  5. public abstract void run();
  6. }

3.2 构造器

  1. /**
  2. * 默认构造器
  3. * 其中name规则为 "Thread-" + nextThreadNum()
  4. */
  5. public Thread() {
  6. init(null, null, "Thread-" + nextThreadNum(), 0);
  7. }
  8. /**
  9. * 创建一个指定Runnable的线程
  10. * 其中name规则为 "Thread-" + nextThreadNum()
  11. */
  12. public Thread(Runnable target) {
  13. init(null, target, "Thread-" + nextThreadNum(), 0);
  14. }
  15. /**
  16. * 创建一个指定所属线程组和Runnable的线程
  17. * 其中name规则为 "Thread-" + nextThreadNum()
  18. */
  19. public Thread(ThreadGroup group, Runnable target) {
  20. init(group, target, "Thread-" + nextThreadNum(), 0);
  21. }
  22. /**
  23. * 创建一个指定name线程
  24. */
  25. public Thread(String name) {
  26. init(null, null, name, 0);
  27. }
  28. /**
  29. * 创建一个指定所属线程组和name的线程
  30. */
  31. public Thread(ThreadGroup group, String name) {
  32. init(group, null, name, 0);
  33. }
  34. /**
  35. * 创建一个指定Runnable和name的线程
  36. */
  37. public Thread(Runnable target, String name) {
  38. init(null, target, name, 0);
  39. }
  40. /**
  41. * Allocates a new {@code Thread} object so that it has {@code target}
  42. * as its run object, has the specified {@code name} as its name,
  43. * and belongs to the thread group referred to by {@code group}.
  44. * 创建一个新的Thread对象,同时满足以下条件:
  45. * 1.该线程拥有一个指定的Runnable对象用于方法执行
  46. * 2.该线程具有一个指定的名称
  47. * 3.该线程属于一个指定的线程组ThreadGroup
  48. * <p>If there is a security manager, its
  49. * {@link SecurityManager#checkAccess(ThreadGroup) checkAccess}
  50. * method is invoked with the ThreadGroup as its argument.
  51. * 若这里有个安全管理器,则ThreadGroup将调用checkAccess方法进而触发SecurityManager的checkAccess方法
  52. * <p>In addition, its {@code checkPermission} method is invoked with
  53. * the {@code RuntimePermission("enableContextClassLoaderOverride")}
  54. * permission when invoked directly or indirectly by the constructor of a subclass which
  55. * overrides the {@code getContextClassLoader} or {@code setContextClassLoader} methods.
  56. * 当enableContextClassLoaderOverride被开启时,checkPermission将被重写子类直接或间接地调用
  57. * <p>The priority of the newly created thread is set equal to the
  58. * priority of the thread creating it, that is, the currently running
  59. * thread. The method {@linkplain #setPriority setPriority} may be
  60. * used to change the priority to a new value.
  61. * 新创建的Thread的优先级等同于创建它的线程的优先级,调用setPriority会变更其优先级
  62. * <p>The newly created thread is initially marked as being a daemon
  63. * thread if and only if the thread creating it is currently marked
  64. * as a daemon thread. The method {@linkplain #setDaemon setDaemon}
  65. * may be used to change whether or not a thread is a daemon.
  66. * 当且仅当线程创建时被显示地标记为守护线程,新创建的线程才会被初始化为一个守护线程
  67. * setDaemon方法可以设置当前线程是否为守护线程
  68. */
  69. public Thread(ThreadGroup group, Runnable target, String name) {
  70. init(group, target, name, 0);
  71. }
  72. /**
  73. * Allocates a new {@code Thread} object so that it has {@code target} as its run object,
  74. * has the specified {@code name} as its name, and belongs to the thread group referred to
  75. * by {@code group}, and has the specified <i>stack size</i>.
  76. * 创建一个新的Thread对象,同时满足以下条件:
  77. * 1.该线程拥有一个指定的Runnable对象用于方法执行
  78. * 2.该线程具有一个指定的名称
  79. * 3.该线程属于一个指定的线程组ThreadGroup
  80. * 4.该线程拥有一个指定的栈容量
  81. * <p>This constructor is identical to {@link #Thread(ThreadGroup,Runnable,String)}
  82. * with the exception of the fact that it allows the thread stack size to be specified.
  83. * The stack size is the approximate number of bytes of address space that the virtual machine
  84. * is to allocate for this thread's stack. <b>The effect of the {@code stackSize} parameter,
  85. * if any, is highly platform dependent.</b>
  86. * 栈容量指的是JVM分配给该线程的栈的地址(内存)空间大小,这个参数的效果高度依赖于JVM运行平台
  87. * <p>On some platforms, specifying a higher value for the {@code stackSize} parameter may allow
  88. * a thread to achieve greater recursion depth before throwing a {@link StackOverflowError}.
  89. * Similarly, specifying a lower value may allow a greater number of threads to exist
  90. * concurrently without throwing an {@link OutOfMemoryError} (or other internal error).
  91. * The details of the relationship between the value of the <tt>stackSize</tt> parameter
  92. * and the maximum recursion depth and concurrency level are platform-dependent.
  93. * <b>On some platforms, the value of the {@code stackSize} parameter
  94. * may have no effect whatsoever.</b>
  95. * 在一些平台上,栈容量越高,(会在栈溢出之前)允许线程完成更深的递归(换句话说就是栈空间更深)
  96. * 同理,若栈容量越小,(在抛出内存溢出之前)允许同时存在更多的线程数
  97. * 对于栈容量、最大递归深度和并发水平之间的关系依赖于平台
  98. * <p>The virtual machine is free to treat the {@code stackSize} parameter as a suggestion.
  99. * If the specified value is unreasonably low for the platform,the virtual machine may instead
  100. * use some platform-specific minimum value; if the specified value is unreasonably high,
  101. * the virtual machine may instead use some platform-specific maximum.
  102. * Likewise, the virtual machine is free to round the specified value up or down as it sees fit
  103. * (or to ignore it completely).
  104. * JVM会将指定的栈容量作为一个参考依据,但当小于平台最小值时会直接使用最小值,最大值同理
  105. * 同样,JVM会动态调整栈空间的大小以适应程序的运行或者甚至直接就忽视该值的设置
  106. * <p><i>Due to the platform-dependent nature of the behavior of this constructor, extreme care
  107. * should be exercised in its use.The thread stack size necessary to perform a given computation
  108. * will likely vary from one JRE implementation to another. In light of this variation,
  109. * careful tuning of the stack size parameter may be required,and the tuning may need to
  110. * be repeated for each JRE implementation on which an application is to run.</i>
  111. * 简单总结一下就是:这个值严重依赖平台,所以要谨慎使用,多做测试验证
  112. * @param group
  113. * the thread group. If {@code null} and there is a security
  114. * manager, the group is determined by {@linkplain
  115. * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
  116. * If there is not a security manager or {@code
  117. * SecurityManager.getThreadGroup()} returns {@code null}, the group
  118. * is set to the current thread's thread group.
  119. * 当线程组为null同时有个安全管理器,该线程组由SecurityManager.getThreadGroup()决定
  120. * 当没有安全管理器或getThreadGroup为空,该线程组即为创建该线程的线程所属的线程组
  121. * @param target
  122. * the object whose {@code run} method is invoked when this thread
  123. * is started. If {@code null}, this thread's run method is invoked.
  124. * 若该值为null,将直接调用该线程的run方法(等同于一个空方法)
  125. * @param name
  126. * the name of the new thread
  127. * @param stackSize
  128. * the desired stack size for the new thread, or zero to indicate
  129. * that this parameter is to be ignored.
  130. * 当栈容量被设置为0时,JVM就会忽略该值的设置
  131. * @throws SecurityException
  132. * if the current thread cannot create a thread in the specified thread group
  133. * 如果当前线程在一个指定的线程组中不能创建一个新的线程时将抛出 安全异常
  134. * @since 1.4
  135. */
  136. public Thread(ThreadGroup group, Runnable target, String name,long stackSize) {
  137. init(group, target, name, stackSize);
  138. }

3.3 JVM栈的异常补充

  • 如果线程请求的栈深度大于虚拟机所允许的深度,将抛出StackOverflowError异常;
  • 如果虚拟机栈可以动态扩展(当前大部分的Java虚拟机都可动态扩展,只不过Java虚拟机规范中也允许固定长度的虚拟机栈),如果扩展时无法申请到足够的内存,就会抛出OutOfMemoryError异常

3.4 重要变量

  1. //线程名,用char来保存(String底层实现就是char)
  2. private char name[];
  3. //线程优先级
  4. private int priority;
  5. //不明觉厉
  6. private Thread threadQ;
  7. //不明觉厉
  8. private long eetop;
  9. /* Whether or not to single_step this thread. 不明觉厉*/
  10. private boolean single_step;
  11. /* Whether or not the thread is a daemon thread. 是否是守护线程,默认非守护线程*/
  12. private boolean daemon = false;
  13. /* JVM state. 是否一出生就领便当,默认false*/
  14. private boolean stillborn = false;
  15. /* What will be run. Thread的run方法最终会调用target的run方法*/
  16. private Runnable target;
  17. /* The group of this thread. 当前线程的所属线程组*/
  18. private ThreadGroup group;
  19. /* The context ClassLoader for this thread 当前线程的ClassLoader*/
  20. private ClassLoader contextClassLoader;
  21. /* The inherited AccessControlContext of this thread 当前线程继承的AccessControlContext*/
  22. private AccessControlContext inheritedAccessControlContext;
  23. /* For autonumbering anonymous threads. 给匿名线程自动编号,并按编号起名字*/
  24. private static int threadInitNumber;
  25. /* ThreadLocal values pertaining to this thread. This map is maintained by the ThreadLocal class.
  26. * 当前线程附属的ThreadLocal,而ThreadLocalMap会被ThreadLocal维护(ThreadLocal会专门分析)
  27. */
  28. ThreadLocal.ThreadLocalMap threadLocals = null;
  29. /*
  30. * InheritableThreadLocal values pertaining to this thread. This map is
  31. * maintained by the InheritableThreadLocal class.
  32. * 主要作用:为子线程提供从父线程那里继承的值
  33. * 在创建子线程时,子线程会接收所有可继承的线程局部变量的初始值,以获得父线程所具有的值
  34. * 创建一个线程时如果保存了所有 InheritableThreadLocal 对象的值,那么这些值也将自动传递给子线程
  35. * 如果一个子线程调用 InheritableThreadLocal 的 get() ,那么它将与它的父线程看到同一个对象
  36. */
  37. ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
  38. /*
  39. * The requested stack size for this thread, or 0 if the creator did not specify a stack size.
  40. * It is up to the VM to do whatever it likes with this number; some VMs will ignore it.
  41. * 栈容量:当设置为0时,JVM会忽略该值;该值严重依赖于JVM平台,有些VM甚至会直接忽视该值
  42. * 该值越大,线程栈空间变大,允许的并发线程数就越少;该值越小,线程栈空间变小,允许的并发线程数就越多
  43. */
  44. private long stackSize;
  45. /* JVM-private state that persists after native thread termination.*/
  46. private long nativeParkEventPointer;
  47. /* Thread ID. 每个线程都有专属ID,但名字可能重复*/
  48. private long tid;
  49. /* For generating thread ID 用于ID生成,每次+1*/
  50. private static long threadSeqNumber;
  51. /*
  52. * Java thread status for tools,initialized to indicate thread 'not yet started'
  53. * 线程状态 0仅表示已创建
  54. */
  55. private volatile int threadStatus = 0;
  56. /**
  57. * The argument supplied to the current call to java.util.concurrent.locks.LockSupport.park.
  58. * Set by (private) java.util.concurrent.locks.LockSupport.setBlocker
  59. * Accessed using java.util.concurrent.locks.LockSupport.getBlocker
  60. * 主要是提供给 java.util.concurrent.locks.LockSupport该类使用
  61. */
  62. volatile Object parkBlocker;
  63. /* The object in which this thread is blocked in an interruptible I/O operation, if any.
  64. * The blocker's interrupt method should be invoked after setting this thread's interrupt status.
  65. * 中断阻塞器:当线程发生IO中断时,需要在线程被设置为中断状态后调用该对象的interrupt方法
  66. */
  67. private volatile Interruptible blocker;
  68. //阻塞器锁,主要用于处理阻塞情况
  69. private final Object blockerLock = new Object();
  70. /* The minimum priority that a thread can have. 最小优先级*/
  71. public final static int MIN_PRIORITY = 1;
  72. /* The default priority that is assigned to a thread. 默认优先级*/
  73. public final static int NORM_PRIORITY = 5;
  74. /* For generating thread ID 最大优先级*/
  75. public final static int MAX_PRIORITY = 10;
  76. /* 用于存储堆栈信息 默认是个空的数组*/
  77. private static final StackTraceElement[] EMPTY_STACK_TRACE = new StackTraceElement[0];
  78. private static final RuntimePermission SUBCLASS_IMPLEMENTATION_PERMISSION =
  79. new RuntimePermission("enableContextClassLoaderOverride");
  80. // null unless explicitly set 线程异常处理器,只对当前线程有效
  81. private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
  82. // null unless explicitly set 默认线程异常处理器,对所有线程有效
  83. private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;

3.5 本地方法

  1. /*
  2. * Make sure registerNatives is the first thing <clinit> does.
  3. * 确保clinit最先调用该方法:所有该方法是类中的最靠前的一个静态方法
  4. * clinit:在JVM第一次加载class文件时调用,用于静态变量初始化语句和静态块的执行
  5. * 所有的类变量初始化语句和类型的静态初始化语句都被Java编译器收集到该方法中
  6. *
  7. * registerNatives方法被native修饰,即是本地方法,将由C/C++去完成,并被编译成了.dll,供JAVA调用
  8. * 其主要作用是将C/C++中的方法映射到Java中的native方法,实现方法命名的解耦
  9. */
  10. private static native void registerNatives();
  11. static {
  12. registerNatives();
  13. }
  14. /** 主动让出CPU资源,当时可能又立即抢到资源 **/
  15. public static native void yield();
  16. /** 休眠一段时间,让出资源但是并不会释放对象锁 **/
  17. public static native void sleep(long millis) throws InterruptedException;
  18. /** 检查 线程是否存活 **/
  19. public final native boolean isAlive();
  20. /** 检查线程是否中断 isInterrupted() 内部使用 **/
  21. private native boolean isInterrupted(boolean ClearInterrupted);
  22. /** 返回当前执行线程 **/
  23. public static native Thread currentThread();
  24. public static native boolean holdsLock(Object obj);
  25. private native void start0();
  26. private native void setPriority0(int newPriority);
  27. private native void stop0(Object o);
  28. private native void suspend0();
  29. private native void resume0();
  30. private native void interrupt0();
  31. private native void setNativeName(String name);

4.线程运行

4.1 init方法

  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. */
  10. private void init(ThreadGroup g, Runnable target, String name,long stackSize) {
  11. if (name == null) {
  12. throw new NullPointerException("name cannot be null");
  13. }
  14. //返回当前线程,即创建该hread的线程 currentThread是个本地方法
  15. Thread parent = currentThread();
  16. //安全管理器根据Java安全策略文件决定将哪组权限授予类
  17. //如果想让应用使用安全管理器和安全策略,可在启动JVM时设定-Djava.security.manager选项
  18. //还可以同时指定安全策略文件
  19. //如果在应用中启用了Java安全管理器,却没有指定安全策略文件,那么Java安全管理器将使用默认的安全策略
  20. //它们是由位于目录$JAVA_HOME/jre/lib/security中的java.policy定义的
  21. SecurityManager security = System.getSecurityManager();
  22. if (g == null) {
  23. /* Determine if it's an applet or not */
  24. /* If there is a security manager, ask the security manager what to do. */
  25. if (security != null) {
  26. g = security.getThreadGroup();
  27. }
  28. /* If the security doesn't have a strong opinion of the matter use the parent thread group. */
  29. if (g == null) {
  30. g = parent.getThreadGroup();
  31. }
  32. }
  33. /* checkAccess regardless of whether or not threadgroup is explicitly passed in. */
  34. //判断当前运行线程是否有变更其线程组的权限
  35. g.checkAccess();
  36. if (security != null) {
  37. if (isCCLOverridden(getClass())) {
  38. security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
  39. }
  40. }
  41. //新建线程数量计数+1 或者说未就绪线程数+1==> nUnstartedThreads++;
  42. g.addUnstarted();
  43. this.group = g;
  44. this.daemon = parent.isDaemon();//若当前运行线程是守护线程,新建线程也是守护线程
  45. this.priority = parent.getPriority();//默认使用当前运行线程的优先级
  46. this.name = name.toCharArray();
  47. //设置contextClassLoader
  48. if (security == null || isCCLOverridden(parent.getClass()))
  49. this.contextClassLoader = parent.getContextClassLoader();
  50. else
  51. this.contextClassLoader = parent.contextClassLoader;
  52. this.inheritedAccessControlContext = AccessController.getContext();
  53. this.target = target;
  54. setPriority(priority);//若有指定的优先级,使用指定的优先级
  55. if (parent.inheritableThreadLocals != null)
  56. this.inheritableThreadLocals =
  57. ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
  58. /* Stash the specified stack size in case the VM cares */
  59. this.stackSize = stackSize;
  60. /* Set thread ID 线程安全,序列号每次同步+1*/
  61. tid = nextThreadID();
  62. }
  63. private static synchronized long nextThreadID() {
  64. return ++threadSeqNumber;
  65. }

4.2 start方法

  1. /**
  2. * Causes this thread to begin execution; the Java Virtual Machine
  3. * calls the <code>run</code> method of this thread.
  4. * 线程进入就绪态,随后JVM将会调用这个线程run方法
  5. * 当获取到CPU时间片时,会立即执行run方法,此时线程会直接变成运行态
  6. * <p>
  7. * The result is that two threads are running concurrently: the
  8. * current thread (which returns from the call to the
  9. * <code>start</code> method) and the other thread (which executes its
  10. * <code>run</code> method).
  11. * <p>
  12. * It is never legal to start a thread more than once.
  13. * In particular, a thread may not be restarted once it has completed execution.
  14. * 一个线程只能被start一次,特别是线程不会在执行完毕后重新start
  15. * 当线程已经start了,再次执行会抛出IllegalThreadStateException异常
  16. * @exception IllegalThreadStateException if the thread was already started.
  17. * @see #run()
  18. * @see #stop()
  19. */
  20. public synchronized void start() {
  21. /**
  22. * This method is not invoked for the main method thread or "system"
  23. * group threads created/set up by the VM. Any new functionality added
  24. * to this method in the future may have to also be added to the VM.
  25. * 该方法不会被主线程或系统线程组调用,若未来有新增功能,也会被添加到VM中
  26. * A zero status value corresponds to state "NEW".
  27. * 0对应"已创建"状态 -> 用常量或枚举标识多好
  28. */
  29. if (threadStatus != 0)
  30. throw new IllegalThreadStateException();
  31. /* Notify the group that this thread is about to be started
  32. * so that it can be added to the group's list of threads
  33. * and the group's unstarted count can be decremented. */
  34. //通知所属线程组该线程已经是就绪状态,因而可以被添加到该线程组中
  35. //同时线程组的未就绪线程数需要-1,对应init中的+1
  36. group.add(this);
  37. boolean started = false;
  38. try {
  39. //调用本地方法,将内存中的线程状态变更为就绪态
  40. //同时JVM会立即调用run方法,获取到CPU之后,线程变成运行态并立即执行run方法
  41. start0();
  42. started = true;//标记为已开启
  43. } finally {
  44. try {
  45. if (!started) {
  46. group.threadStartFailed(this);//如果变更失败,要回滚线程和线程组状态
  47. }
  48. } catch (Throwable ignore) {
  49. /* do nothing. If start0 threw a Throwable then
  50. it will be passed up the call stack */
  51. //如果start0出错,会被调用栈直接通过
  52. }
  53. }
  54. }
  55. -------------
  56. //start之后会立即调用run方法
  57. Thread t = new Thread( new Runnable() {
  58. @Override
  59. public void run() {
  60. System.out.println(Thread.currentThread().getName());
  61. }
  62. },"kira");
  63. t.start();//kira

4.3 run方法

  1. /**
  2. * If this thread was constructed using a separate <code>Runnable</code> run object,
  3. * then that <code>Runnable</code> object's <code>run</code> method is called;
  4. * otherwise, this method does nothing and returns.
  5. * Subclasses of <code>Thread</code> should override this method.
  6. * 若Thread初始化时有指定Runnable就执行其的run方法,否则doNothing
  7. * 该方法必须被子类实现
  8. */
  9. @Override
  10. public void run() {
  11. if (target != null) {
  12. target.run();
  13. }
  14. }

4.4 isAlive方法

  1. /**
  2. * Tests if this thread is alive. A thread is alive if it has
  3. * been started and has not yet died.
  4. * 测试线程是否处于活动状态
  5. * 活动状态:线程处于正在运行或者准备开始运行状态
  6. * @return <code>true</code> if this thread is alive;
  7. * <code>false</code> otherwise.
  8. */
  9. public final native boolean isAlive();

5.线程暂停

5.1 JAVA暂停线程的方法

  • 暂停线程意味着线程还可以重新恢复
  • JAVA提供多种暂停的方式:suspend()和resume()组合sleep()join()yield()wait()和notify()组合
  • 其中join()wait()和notify() 将放在 线程间通信 中进一步讲解
  • suspend()和resume()组合 作为线程间的通信方式已被官方弃用,官方推荐使用wait()和notify()组合替换前者

5.2 suspend方法和resume方法

  1. /**
  2. * Suspends this thread.
  3. * If the thread is alive, it is suspended and makes no further progress
  4. * unless and until it is resumed.
  5. * 暂停当前线程:若当前线程还活着,将被暂停同时直到被恢复之前都不会做任何事
  6. */
  7. @Deprecated
  8. public final void suspend() {
  9. checkAccess();
  10. suspend0();
  11. }
  12. /**
  13. * Resumes a suspended thread.
  14. * If the thread is alive but suspended, it is resumed and is
  15. * permitted to make progress in its execution.
  16. * 恢复一个被暂停的线程:若线程活着同时被暂停,恢复它同时允许它继续执行后续行为
  17. */
  18. @Deprecated
  19. public final void resume() {
  20. checkAccess();
  21. resume0();
  22. }

5.3 suspend/resume 组合的问题

  • 独占
  1. //如果使用不当,很容易造成公共的同步对象的独占,是其他线程无法访问公共同步对象
  2. public class ThreadDemo {
  3. synchronized void echo(){
  4. System.out.println("开始任务");
  5. if (Thread.currentThread().getName().equals("sally")){
  6. System.out.println("sally线程执行suspend方法并永远暂停");
  7. Thread.currentThread().suspend();
  8. }
  9. }
  10. public static void main(String[] args) throws InterruptedException {
  11. final ThreadDemo threadDemo = new ThreadDemo();
  12. Thread t1 = new Thread(new Runnable() {
  13. @Override
  14. public void run() {
  15. threadDemo.echo();
  16. }
  17. }, "sally");
  18. t1.start();
  19. Thread t2 = new Thread(new Runnable() {
  20. @Override
  21. public void run() {
  22. System.out.println("kira线程启动,但无法执行echo方法");
  23. //因为echo方法被sally线程锁定并且永远suspend暂停了,无法释放,即独占
  24. threadDemo.echo();
  25. }
  26. }, "kira");
  27. t2.start();
  28. }
  29. }
  30. -------------
  31. //输出:
  32. 开始任务
  33. sally线程执行suspend方法
  34. kira线程启动,但无法执行echo方法
  • 不同步
  1. //如果使用不当,也容易出现因为线程的暂停而导致线程不同步的问题
  2. public class ThreadDemo {
  3. private String value = "战狼1";
  4. public String getValue() {
  5. return value;
  6. }
  7. public void setValue(String value) {
  8. if (Thread.currentThread().getName().equals("sally")){
  9. System.out.println("停止sally线程");
  10. Thread.currentThread().suspend();
  11. }
  12. this.value = value;
  13. }
  14. public static void main(String[] args) throws InterruptedException {
  15. final ThreadDemo threadDemo = new ThreadDemo();
  16. Thread t1 = new Thread(new Runnable() {
  17. @Override
  18. public void run() {
  19. threadDemo.setValue("战狼2");
  20. }
  21. }, "sally");
  22. t1.start();
  23. Thread.sleep(1000);
  24. Thread t2 = new Thread(new Runnable() {
  25. @Override
  26. public void run() {
  27. System.out.println(threadDemo.getValue());
  28. }
  29. }, "kira");
  30. t2.start();
  31. }
  32. }
  33. //输出:
  34. 停止sally线程
  35. 战狼1 --> 很明显,由于线程暂停,得到的不是想要的战狼2

5.4 sleep方法

  1. /**
  2. * Causes the currently executing thread to sleep (temporarily cease execution)
  3. * for the specified number of milliseconds plus the specified number of nanoseconds,
  4. * subject to the precision and accuracy of system timers and schedulers.
  5. * The thread does not lose ownership of any monitors.
  6. * 使线程睡眠一段毫秒时间,但线程并不会丢失已有的任何监视器
  7. */
  8. public static void sleep(long millis, int nanos) throws InterruptedException {
  9. if (millis < 0) {
  10. throw new IllegalArgumentException("timeout value is negative");
  11. }
  12. if (nanos < 0 || nanos > 999999) {
  13. throw new IllegalArgumentException("nanosecond timeout value out of range");
  14. }
  15. //换算用
  16. if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
  17. millis++;
  18. }
  19. sleep(millis);
  20. }
  21. /** 我们一般会直接调用native方法,这或许是我们主动使用的最多次的native方法了 **/
  22. public static native void sleep(long millis) throws InterruptedException;

5.5 yield方法

  1. /**
  2. * A hint to the scheduler that the current thread is willing to yield
  3. * its current use of a processor. The scheduler is free to ignore this hint.
  4. * 暗示线程调度器当前线程将释放自己当前占用的CPU资源
  5. * 线程调度器会自由选择是否忽视此暗示
  6. * <p> Yield is a heuristic attempt to improve relative progression
  7. * between threads that would otherwise over-utilise a CPU. Its use
  8. * should be combined with detailed profiling and benchmarking to
  9. * ensure that it actually has the desired effect.
  10. * 该方法会放弃当前的CPU资源,将它让给其他的任务去占用CPU执行时间
  11. * 但放弃的时间不确定,可能刚刚放弃又获得CPU时间片
  12. * <p> It is rarely appropriate to use this method. It may be useful
  13. * for debugging or testing purposes, where it may help to reproduce
  14. * bugs due to race conditions. It may also be useful when designing
  15. * concurrency control constructs such as the ones in the
  16. * {@link java.util.concurrent.locks} package.
  17. * 该方法的适合使用场景比较少,主要用于Debug,比如Lock包设计
  18. */
  19. public static native void yield();
  1. Thread t1 = new Thread(new Runnable() {
  2. @Override
  3. public void run() {
  4. long begin = System.currentTimeMillis();
  5. int count = 0;
  6. for (int i = 1;i<1000000;i++){
  7. //Thread.yield();
  8. count += i;
  9. }
  10. long end = System.currentTimeMillis();
  11. System.out.println("耗时:" + (end - begin) + "毫秒!");
  12. }
  13. }, "sally");
  14. t1.start();
  15. -------------
  16. //当Thread.yield()被注释时,输出: 耗时:1毫秒!
  17. //当Thread.yield()放开注释时,输出: 耗时:125毫秒!
  18. //可以发现,两者差距还是有的

6.线程终止

6.1 JAVA终止线程的方法

  1. 使用退出标识,使线程正常退出,即当run()方法完成之后线程自动终止
  2. 使用stop()方法强行终止,但该方法已被弃用,使用它们可能产生不可预料的后果
  3. 使用interrupt()方法中断线程

6.2 interrupt方法

  1. /**
  2. * Interrupts this thread.
  3. * 中断一个线程
  4. * <p> Unless the current thread is interrupting itself, which is always permitted,
  5. * the {@link #checkAccess() checkAccess} method of this thread is invoked,
  6. * which may cause a {@link SecurityException} to be thrown.
  7. * 如果当前线程不是被自己中断,可能会抛出SecurityException异常
  8. * <p> If this thread is blocked in an invocation of the {@link Object#wait() wait()},
  9. * {@link Object#wait(long) wait(long)}, or {@link Object#wait(long, int) wait(long, int)}
  10. * methods of the {@link Object} class, or of the {@link #join()}, {@link #join(long)}, {@link
  11. * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},methods of this class,
  12. * then its interrupt status will be cleared and it will receive an {@link InterruptedException}.
  13. * 若当前线程已被Object.wait()方法、Thread的join()或sleep方法阻塞,
  14. * 则调用该中断方法会抛出InterruptedException同时中断状态会被清除
  15. * <p> If this thread is blocked in an I/O operation upon an {@link
  16. * java.nio.channels.InterruptibleChannel </code>interruptible channel<code>}
  17. * then the channel will be closed, the thread's interrupt status will be set,
  18. * and the thread will receive a {@link java.nio.channels.ClosedByInterruptException}.
  19. * 若当前线程在InterruptibleChannel上发生IO阻塞,该通道要被关闭并将线程状态设置为中断同时抛出
  20. * ClosedByInterruptException异常
  21. * <p> If this thread is blocked in a {@link java.nio.channels.Selector} then the thread's
  22. * interrupt status will be set and it will return immediately from the selection operation,
  23. * possibly with a non-zero value, just as if the selector's {@link
  24. * java.nio.channels.Selector#wakeup wakeup} method were invoked.
  25. * 若该线程被选择器阻塞,将线程状态设置为中断同时从选取方法中立即返回
  26. * 该选取方法通常会返回一个非0值,当wakeup方法正好被调用时
  27. * <p> If none of the previous conditions hold then this thread's interrupt status will be set. </p>
  28. * 非上述情况都会将线程状态设置为中断
  29. * <p> Interrupting a thread that is not alive need not have any effect.
  30. * 中断一个非活线程不会有啥影响
  31. * @throws SecurityException if the current thread cannot modify this thread
  32. * @revised 6.0
  33. * @spec JSR-51
  34. */
  35. public void interrupt() {
  36. if (this != Thread.currentThread())
  37. checkAccess();
  38. synchronized (blockerLock) {
  39. Interruptible b = blocker;
  40. if (b != null) {
  41. // Just to set the interrupt flag
  42. // 调用interrupt方法仅仅是在当前线程中打了一个停止的标记,并不是真的停止线程!
  43. interrupt0();
  44. b.interrupt(this);
  45. return;
  46. }
  47. }
  48. interrupt0();
  49. }

6.3 isInterrupted方法

  1. /**
  2. * Tests whether this thread has been interrupted.
  3. * The <i>interruptedstatus< /i> of the thread is unaffected by this method.
  4. * 测试线程Thread对象是否已经是中断状态,但不清除状态标志
  5. * @return <code>true</code> if this thread has been interrupted;
  6. * <code>false</code> otherwise.
  7. * @see #interrupted()
  8. * @revised 6.0
  9. */
  10. public boolean isInterrupted() {
  11. //会调用本地isInterrupted方法,同时不清除状态标志
  12. return isInterrupted(false);
  13. }
  14. /**
  15. * @param ClearInterrupted 是否清除状态标注,false不清除,true清除
  16. */
  17. private native boolean isInterrupted(boolean ClearInterrupted);
  18. -------------
  19. Thread t2 = new Thread(new Runnable() {
  20. @Override
  21. public void run() {
  22. for (int i = 0 ;i < 10000;i++){}
  23. System.out.println(Thread.currentThread().getName());
  24. }
  25. },"kira");
  26. t2.start();
  27. t2.interrupt();
  28. System.out.println("是否停止 1 ?= " + t2.isInterrupted());//是否停止 1 ?=true
  29. System.out.println("是否停止 2 ?= " + t2.isInterrupted());//是否停止 2 ?=true

6.4 interrupted方法

  1. /**
  2. * Tests whether the current thread has been interrupted.
  3. * The <i>interrupted status</i> of the thread is cleared by this method.
  4. * In other words, if this method were to be called twice in succession, the
  5. * second call would return false (unless the current thread were interrupted again,after the
  6. * first call had cleared its interrupted status and before the second call had examined it).
  7. * 测试当前线程是否已经是中断状态,执行后具有将状态标志清除为false的功能
  8. * 当连续两次调用该方法时,第二次会返回false(除非该线程再次被中断)
  9. * @return <code>true</code> if the current thread has been interrupted;
  10. * <code>false</code> otherwise.
  11. * @see #isInterrupted()
  12. * @revised 6.0
  13. */
  14. public static boolean interrupted() {
  15. //当前线程会调用本地isInterrupted方法,同时不清除状态标志
  16. //注意比isInterrupted方法多了个currentThread
  17. return currentThread().isInterrupted(true);
  18. }
  19. -------------
  20. Thread t2 = new Thread(new Runnable() {
  21. @Override
  22. public void run() {
  23. for (int i = 0 ;i < 10000;i++){}
  24. System.out.println(Thread.currentThread().getName());
  25. }
  26. },"kira");
  27. t2.start();
  28. t2.interrupt();//此时currentThread指的是主线程,主线程并没有被中断(执行了out方法),因此返回false
  29. System.out.println("是否停止 1 ?= " + t2.interrupted());//是否停止 1 ?=fasle
  30. System.out.println("是否停止 2 ?= " + t2.interrupted());//是否停止 2 ?=fasle
  31. //将t2.interrupt()变成下面的,则主线程被中断
  32. Thread.currentThread().interrupt();
  33. System.out.println("是否停止 1 ?= " + t2.interrupted());//是否停止 1 ?=true

6.5 终止线程

  • 注意:interrupt()方法只是建议中断而不是真正中断,所以需要用以下方法真正终止线程
  • 异常法
  1. //直接选择在run方法中抛出异常,从而停止线程
  2. Thread t2 = new Thread(new Runnable() {
  3. @Override
  4. public void run() {
  5. try {
  6. throw new InterruptedException();//主动抛出异常
  7. } catch (InterruptedException e) {
  8. System.out.println("成功捕获 InterruptedException异常");
  9. e.printStackTrace();
  10. }
  11. }
  12. },"kira");
  13. t2.start();
  14. t2.interrupt();
  15. -------------
  16. //输出:成功捕获 InterruptedException异常
  17. //打印:java.lang.InterruptedException
  • 沉睡法
  1. //沉睡
  2. Thread t2 = new Thread(new Runnable() {
  3. @Override
  4. public void run() {
  5. try {
  6. Thread.sleep(1000);//沉睡
  7. } catch (InterruptedException e) {
  8. System.out.println("在沉睡中 成功捕获 InterruptedException异常");
  9. e.printStackTrace();
  10. }
  11. }
  12. },"kira");
  13. t2.start();
  14. t2.interrupt();
  15. -------------
  16. //输出:在沉睡中 成功捕获 InterruptedException异常
  17. //打印:java.lang.InterruptedException: sleep interrupted
  • Return法
  1. //j将interrupt方法与return结合使用也能停止线程
  2. Thread t2 = new Thread(new Runnable() {
  3. @Override
  4. public void run() {
  5. int i = 0;
  6. while (true){
  7. if (Thread.currentThread().isInterrupted()){
  8. System.out.println("停止");
  9. return;
  10. }
  11. System.out.println(System.currentTimeMillis());
  12. }
  13. }
  14. },"kira");
  15. t2.start();
  16. Thread.sleep(1000);
  17. t2.interrupt();
  18. -------------
  19. //输出:
  20. .....
  21. 1502463392035
  22. 1502463392035
  23. 1502463392035
  24. 停止
  25. //然后就停止打印了
  • 暴力法
  1. //使用stop()方法停止线程是非常暴力的,不能用!
  2. Thread t2 = new Thread(new Runnable() {
  3. @Override
  4. public void run() {
  5. int i = 0;
  6. while (true){
  7. System.out.println(i++);
  8. }
  9. }
  10. },"kira");
  11. t2.start();
  12. Thread.sleep(1000);
  13. t2.stop();
  14. -------------
  15. //输出:
  16. .....
  17. 154192
  18. 154193
  19. 154194
  20. 154195
  21. //然后就停止打印了
  • 禁用stop方法的原因
  • 情况1:即刻抛出ThreadDeath异常,在线程的run()方法内,任何一点都有可能抛出ThreadDeath Error,包括在catch或finally语句中
  • 情况2:释放该线程所持有的所有的锁,会导致数据无法同步处理,出现数据不一致的问题
  1. //情况1:使用stop()方法时会抛出ThreadDeath异常,但一般不需要显示捕获
  2. Thread t2 = new Thread(new Runnable() {
  3. @Override
  4. public void run() {
  5. try {
  6. Thread.currentThread().stop();
  7. }catch (ThreadDeath death){
  8. System.out.println("捕获到ThreadDeath异常");
  9. death.printStackTrace();
  10. }
  11. }
  12. },"kira");
  13. t2.start();
  14. -------------
  15. //输出:捕获到ThreadDeath异常
  16. //打印:java.lang.ThreadDeath
  1. //情况2:使用stop()方法释放锁会给数据造成不一样的问题
  2. final Object lock = new Object();
  3. Thread t1 = new Thread(new Runnable() {
  4. @Override
  5. public void run() {
  6. try {
  7. synchronized (lock) {
  8. System.out.println(Thread.currentThread().getName() + "获取锁");
  9. Thread.sleep(1000);
  10. System.out.println(Thread.currentThread().getName() + "释放锁");
  11. }
  12. } catch (Throwable ex) {
  13. System.out.println("获取异常: " + ex);
  14. ex.printStackTrace();
  15. }
  16. }
  17. },"sally");
  18. Thread t2 = new Thread(new Runnable() {
  19. @Override
  20. public void run() {
  21. synchronized (lock) {
  22. System.out.println(Thread.currentThread().getName() + "获取锁");
  23. }
  24. }
  25. },"kira");
  26. t1.start();
  27. Thread.sleep(1000);
  28. // t1.stop();
  29. t2.start();
  30. -------------
  31. //当t1.stop()未执行时,两个线程竞争锁的顺序是固定的,打印结果如下:
  32. sally获取锁
  33. sally释放锁
  34. kira获取锁
  35. //当t1.stop()执行时,t1线程抛出了ThreadDeath异常并且t1线程释放了它所占有的锁,打印结果如下:
  36. kira获取锁
  37. java.lang.ThreadDeath
  38. 获取异常: java.lang.ThreadDeath
  39. //由上述可得,stop方法非线性安全,再加上是过期方法,一定不能用!

7.线程优先级

7.1 setPriority方法

  1. /**
  2. * Changes the priority of this thread.
  3. * 变更线程优先级 默认优先级为NORM_PRIORITY = 5
  4. */
  5. public final void setPriority(int newPriority) {
  6. ThreadGroup g;
  7. checkAccess();
  8. //优先级区间时MIN_PRIORITY - MAX_PRIORITY
  9. //注意:不同操作系统的优先级可能有些区别
  10. if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
  11. throw new IllegalArgumentException();
  12. }
  13. if((g = getThreadGroup()) != null) {
  14. if (newPriority > g.getMaxPriority()) {
  15. newPriority = g.getMaxPriority();
  16. }
  17. setPriority0(priority = newPriority);
  18. }
  19. }

7.2 优先级规则

  • 继承性
  1. //线程t1启动线程t2,则t2与t1具有相同的优先级
  2. Thread t1 = new Thread(new Runnable() {
  3. @Override
  4. public void run() {
  5. System.out.println("当前线程" + Thread.currentThread().getName() + "的优先级为:" + Thread.currentThread().getPriority());
  6. new Thread(new Runnable() {
  7. @Override
  8. public void run() {
  9. System.out.println("当前线程" + Thread.currentThread().getName() + "的优先级为:" + Thread.currentThread().getPriority());
  10. }
  11. },"kira").start();
  12. }
  13. }, "sally");
  14. t1.setPriority(Thread.MAX_PRIORITY);//注意默认优先级是5,这里我们改成10
  15. t1.start();
  16. -------------
  17. //输出:
  18. 当前线程sally的优先级为:10
  19. 当前线程kira的优先级为:10
  • 规则性
  • CPU会尽量将执行资源让给优先级比较高的线程
  • 高优先级的线程总是大部分先执行完,但不意味着高优先级的线程会先全部执行完
  • 当线程优先级的等级差距很大时,谁先执行完和代码的调用顺序无关
  • 随机性
  • 优先级高的线程不一定每次都先执行完,具有随机性和不确定性
  • 但通常来说,优先级高的线程都会运行的比优先级较低的要快(大概率事件)

8.线程异常处理

8.1 线程中异常处理

  • 线程中异常处理方法
  • 在Java中可以对多线程中的异常进行捕获,是通的是UncaughtException类,从而对可能发生的异常进行有效处理
  • setUncaughtExceptionHandler() 是给指定线程对象设置的异常处理器
  • setDefaultUncaughtExceptionHandler()是给所有线程对象设置默认的异常处理器
  • setUncaughtExceptionHandler() 优先级高于 setDefaultUncaughtExceptionHandler()
  • 补充一句:由于一般情况都是使用线程池,针对线程池异常会专门在 并发番@线程池一文通 中讲解
  • setUncaughtExceptionHandler
  1. Thread t2 = new Thread(new Runnable() {
  2. @Override
  3. public void run() {
  4. Object object = null;
  5. System.out.println(object.toString());
  6. }
  7. },"kira");
  8. //setUncaughtExceptionHandler()是给指定线程对象设置的异常处理器
  9. //同时setUncaughtExceptionHandler()优先级高于setDefaultUncaughtExceptionHandler()
  10. t2.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
  11. @Override
  12. public void uncaughtException(Thread t, Throwable e) {
  13. System.out.println(t.getName() + "线程出现异常");
  14. e.printStackTrace();
  15. }
  16. });
  17. t2.start();
  18. -------------
  19. //输出:
  20. kira线程出现异常
  21. java.lang.NullPointerException
  22. at concurrent.Main$1.run(Main.java:12)
  23. at java.lang.Thread.run(Thread.java:748)
  • setDefaultUncaughtExceptionHandler
  1. //setDefaultUncaughtExceptionHandler()是给所有线程对象设置默认的异常处理器
  2. //同时setUncaughtExceptionHandler()优先级高于setDefaultUncaughtExceptionHandler()
  3. Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
  4. @Override
  5. public void uncaughtException(Thread t, Throwable e) {
  6. System.out.println(t.getName() + "线程出现异常");
  7. e.printStackTrace();
  8. }
  9. });
  10. Thread t2 = new Thread(new Runnable() {
  11. @Override
  12. public void run() {
  13. Object object = null;
  14. System.out.println(object.toString());
  15. }
  16. },"kira");
  17. t2.start();
  18. -------------
  19. //输出:
  20. kira线程出现异常
  21. java.lang.NullPointerException
  22. at concurrent.Main$1.run(Main.java:12)
  23. at java.lang.Thread.run(Thread.java:748)

8.2 线程组异常处理

  • 线程组异常特点
  • 默认情况下,同一个线程组的线程出现异常,该线程组的并不会受到影响并被终止,而是继续正常运行
  • 若想实现同一个线程组的中一旦有一个线程出现异常要终止该线程组的所有线程时,需要继承 ThreadGroup 同时重写 ThreadGroup 的重写 uncaughtException()方法
  • 继承ThreadGroup
  1. /**
  2. * 继承ThreadGroup自定义一个新的线程组,并重写uncaughtException方法
  3. * 实现:当线程组内一个线程出现异常,该线程组下的所有线程也会全部停止
  4. */
  5. public class KiraThreadGroup extends ThreadGroup {
  6. public KiraThreadGroup(String name) {
  7. super(name);
  8. }
  9. //重写线程组的uncaughtException方法
  10. @Override
  11. public void uncaughtException(Thread t, Throwable e) {
  12. super.uncaughtException(t, e);
  13. this.interrupt();//出现异常,就终止该线程
  14. }
  15. }
  16. -------------
  17. KiraThreadGroup kiraThreadGroup = new KiraThreadGroup("kiraGroup");
  18. Thread [] threads = new Thread[5];
  19. for (int i =0;i<5;i++){
  20. threads[i] = new Thread(kiraThreadGroup,new Runnable() {
  21. @Override
  22. public void run() {
  23. Thread t = Thread.currentThread();
  24. if ("kira4".equals(t.getName())){
  25. throw new NullPointerException();//随便抛出一个异常
  26. }
  27. while (t.isInterrupted() == false){
  28. System.out.println("线程" + t.getName() + "死循环中");
  29. }
  30. }
  31. },"kira" + i);
  32. threads[i].start();
  33. -------------
  34. //输出:
  35. .....
  36. 线程kira1死循环中
  37. 线程kira1死循环中
  38. 线程kira0死循环中
  39. 线程kira3死循环中
  40. Exception in thread "kira4" java.lang.NullPointerException
  41. at concurrent.Main$1.run(Main.java:17)
  42. at java.lang.Thread.run(Thread.java:748)
  43. //然后所有线程都终止了,结束打印

9.守护线程

9.1 守护线程

  • 分类:在JAVA中分成两种线程:用户线程守护线程
  • 特性:当进程中不存在非守护线程时,则全部的守护线程会自动化销毁
  • 应用: JVM在启动后会生成一系列守护线程,最有名的当属GC(垃圾回收器)

9.2 守护线程的使用

  1. Thread t2 = new Thread(new Runnable() {
  2. @Override
  3. public void run() {
  4. System.out.println("守护线程运行了");
  5. for (int i = 0; i < 500000;i++){
  6. System.out.println("守护线程计数:" + i);
  7. }
  8. }
  9. }, "kira");
  10. t2.setDaemon(true);
  11. t2.start();
  12. Thread.sleep(500);
  13. -------------
  14. //输出:
  15. ......
  16. 守护线程计数:113755
  17. 守护线程计数:113756
  18. 守护线程计数:113757
  19. 守护线程计数:113758
  20. //结束打印:会发现守护线程并没有打印500000次,因为主线程已经结束运行了

10.线程间通信

10.1 线程间通信

  • 线程与线程之间不是独立的个体,彼此之间可以互相通信和协作
  • Java提供多种线程间通信方案:轮询机制等待/通知机制join方法ThreadLocalsynchronizedvolatile
  • volitile 请参见笔者的 并发番@Volatile一文通 (排期中)
  • synchronized 请参见笔者的 并发番@Synchronized一文通 (排期中)
  • ThreadLocal 请参见笔者的 并发番@ThreadLocal一文通 (排期中)

10.2 轮询机制

  • Sleep + While(true)
  1. final List<Integer> list = new ArrayList<Integer>();
  2. Thread t1 = new Thread(new Runnable() {
  3. @Override
  4. public void run() {
  5. try {
  6. for (int i = 0 ; i < 6 ;i++){
  7. list.add(i);
  8. System.out.println("添加了" + (i+1) + "个元素");
  9. }
  10. Thread.sleep(1000);
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. },"sally");
  16. Thread t2 = new Thread(new Runnable() {
  17. @Override
  18. public void run() {
  19. try {
  20. while (true){
  21. if (list.size() == 3){
  22. System.out.println("已添加5个元素,kira线程需要退出");
  23. throw new InterruptedException();
  24. }
  25. }
  26. } catch (InterruptedException e) {
  27. e.printStackTrace();//这里只是打印堆栈信息,不是真的停止执行
  28. }
  29. }
  30. },"kira");
  31. t1.start();
  32. t2.start();
  33. -------------
  34. //输出:
  35. 添加了1个元素
  36. 添加了2个元素
  37. 添加了3个元素
  38. 已添加3个元素,kira线程需要退出
  39. java.lang.InterruptedException
  40. at concurrent.Main$2.run(Main.java:98)
  41. at java.lang.Thread.run(Thread.java:748)
  42. 添加了4个元素
  43. 添加了5个元素
  44. 添加了6个元素
  • 轮询机制的弊端
  • 难以保证及时性:睡眠时,基本不消耗资源,但睡眠时间过长(轮询间隔时间较大),就不能及时发现条件变更
  • 难以降低开销:减少睡眠时间(轮训间隔时间较小),能更迅速发现变化,但会消耗更多资源,造成无端浪费
  • Java引入等待/通知机制来减少CPU的资源浪费,同时还可以时间在多个线程间的通信

10.3 等待/通知机制

  • Object类的wait和notify方法

image_1bng05nfa14ij3as3eab3ode8l.png-89.1kB

  • Object.wait方法
  • wait方法使当前线程进行等待,该方法是Object类的方法,用来将当前线程放入"等待队列"中,并在wait所在的代码处停止执行,直到收到通知被唤醒或被中断或超时
  • 调用wait方法之前,线程必须获得该对象的对象级别锁,即只能在同步方法或同步块中调用wait方法
  • 在执行wait方法后,当前线程释放锁,在从wait方法返回前,线程与其他线程竞争重新获得锁
  • 如果调用wait方法时没有持有适当的锁,则抛出运行期异常类IllegalMonitorStateException
  • Object.notify方法
  • notify方法使线程被唤醒,该方法是Object类的方法,用来将当前线程从"等待队列中"移出到"同步队列中",线程状态重新变成阻塞状态,notify方法所在同步块释放锁后,从wait方法返回继续执行
  • 调用notify方法之前,线程必须获得该对象的对象级别锁,即只能在同步方法或同步块中调用notify方法
  • 该方法用来通知那么可能等待该对象的对象锁的其他线程,如果有多个线程等待,则由线程规划器从等待队列中随机选择一个WAITING状态线程,对其发出通知转入同步队列并使它等待获取该对象的对象锁
  • 在执行notify方法之后,当前线程不会马上释放对象锁,等待线程也并不能马上获取该对象锁,需要等到执行notify方法的线程将程序执行完,即退出同步代码块之后当前线程才能释放锁,而等待线程才可以有机会获取该对象锁
  • 如果调用notify方法时没有持有适当的锁,则抛出运行期异常类IllegalMonitorStateException
  • wait/notify机制

wait()使线程停止运行,notify()使停止的线程继续运行
1). 使用wait()notify()notifyAll()需要先对调用对象加锁,即只能在同步方法或同步块中调用这些方法
2). 调用wait()方法后,线程状态由RUNNING变成WAITING,并将当前线程放入对象的等待队列
3). 调用notify()notifyAll()方法之后,等待线程不会从wait()返回,需要notify()方法所在同步块代码执行完毕而释放锁之后,等待线程才可以获取到该对象锁并从wait()返回
4). notify()方法将随机选择一个等待线程从等待队列中移到同步队列中;notifyAll()方法会将等待队列中的所有等待线线程全部移到同步队列中,被移动线程状态由WAITING变成BLOCKED

  • 等待/通知的经典范式(生产者-消费者模式)

  • 等待方(生产者)遵循如下规则

1) 获取对象的锁
2) 如果条件不满足,那么调用对象的wait方法,被通知后仍要检查条件
3) 条件满足则执行对应处理逻辑

  1. //对应伪代码
  2. synchrozied(对象){
  3. while(条件不满足){
  4. 对象.wait();
  5. }
  6. 对应处理逻辑
  7. }
  • 通知方(消费者)遵循如下规则

1) 获取对象的锁
2) 改变条件
3) 通知所有等待在对象上的线程

  1. //对应伪代码
  2. synchrozied(对象){
  3. 改变条件
  4. 对象.notifyAll();
  5. }
  • wait/notify的使用
  1. final List<Integer> list = new ArrayList<Integer>();
  2. Object lock = new Object();
  3. Thread t1 = new Thread(new Runnable() {
  4. @Override
  5. public void run() {
  6. //加锁,拥有lock的Monitor
  7. //wait方法必须在synchronized方法或方法块中执行,否则抛出IllegalMonitorStateException
  8. synchronized (lock){
  9. System.out.println(Thread.currentThread().getName() + "线程开始执行");
  10. if (list.size() != 3){
  11. System.out.println("wait 开始:" + System.currentTimeMillis());
  12. try {
  13. lock.wait();//将当前sally线程放入等待队列中,进入等待状态
  14. System.out.println("wait 结束:" + System.currentTimeMillis());
  15. System.out.println(Thread.currentThread().getName() + "线程结束执行");
  16. } catch (InterruptedException e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. }
  21. }
  22. },"sally");
  23. Thread t2 = new Thread(new Runnable() {
  24. @Override
  25. public void run() {
  26. //加锁,拥有lock的Monitor
  27. //notify方法必须在synchronized方法或方法块中执行,否则抛出IllegalMonitorStateException
  28. //由于wait方法会释放锁,所以kira线程可以获取到lock同步锁
  29. //同时notify方法不会释放锁,直到该同步块执行完毕
  30. synchronized (lock){
  31. try {
  32. System.out.println(Thread.currentThread().getName() + "线程开始执行");
  33. for (int i = 0; i< 6;i++){
  34. list.add(i);
  35. if (list.size() == 3){
  36. System.out.println("notify 开始:" + System.currentTimeMillis());
  37. //随机唤醒一个等待线程,这里因为就只有sally线程被等待,所有就唤醒它
  38. lock.notify();
  39. // lock.notifyAll(); 会一次性唤醒所有的等待线程
  40. System.out.println("notify方法已执行,发出通知");
  41. }
  42. System.out.println("已添加" + ( i +1 ) + "个元素");
  43. Thread.sleep(500);//为了让效果明显一些,我们先暂停500毫秒
  44. }
  45. System.out.println("notify 结束:" + System.currentTimeMillis());
  46. System.out.println(Thread.currentThread().getName() + "线程结束执行");
  47. } catch (InterruptedException e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. }
  52. },"kira");
  53. t1.start();
  54. t2.start();
  55. -------------
  56. //输出:
  57. sally线程开始执行
  58. wait 开始:1502699526681
  59. 执行wait方法
  60. kira线程开始执行 //注意:wait方法会释放锁,所有kira线程获得锁从而执行
  61. 已添加1个元素
  62. 已添加2个元素
  63. notify 开始:1502699527682
  64. notify已方法,发出通知
  65. 已添加3个元素
  66. 已添加4个元素
  67. 已添加5个元素
  68. 已添加6个元素 //注意:notify方法不会释放锁,直到该同步方法/块执行完毕才会释放锁
  69. notify 结束:1502699529682
  70. kira线程结束执行
  71. wait 结束:1502699529682
  72. sally线程结束执行
  • wait/notify的陷阱
  • 通知过早: 当notify执行的过早,或者说通知过早,很容易造成逻辑混乱,比如wait失效
  • 等待条件变化: 当wait等待的条件发生了变化,很容易造成逻辑混乱,比如异常

10.4 join方法

  • join方法
  • 作用:等待线程对象销毁,可以使得一个线程在另一个线程结束后再执行,底层使用wait()实现
  • 常用于: 将两个交替执行的线程合并为顺序执行的线程
  • 场景: 在很多情况下,主线程创建并启动子线程,当子线程中要进行大量耗时运算,主线程往往将早于子线程结束之前结束。这时,如果主线程想等待子线程执行完成之后再结束,比如子线程处理一个数据,主线程要取得这个数据中的值,就可以使用join()方法
  • join方法解析
  1. /**
  2. * Waits at most {@code millis} milliseconds for this thread to
  3. * die. A timeout of {@code 0} means to wait forever.
  4. * 后续线程需要等待当前线程至多运行millis毫秒(超过millis当前线程会自动死亡,结束等待)
  5. * 若millis表示0,表示后续线程需要永远等待(直到当前线程运行完毕)
  6. * <p> This implementation uses a loop of {@code this.wait} calls conditioned on
  7. * {@code this.isAlive}. As a thread terminates the {@code this.notifyAll} method is invoked.
  8. * It is recommended that applications not use {@code wait}, {@code notify}, or
  9. * {@code notifyAll} on {@code Thread} instances.
  10. * 该方法的原理是循环调用wait方法阻塞后续线程直到当前线程已经不是存活状态了
  11. * @param millis
  12. * the time to wait in milliseconds
  13. * @throws IllegalArgumentException
  14. * if the value of {@code millis} is negative
  15. * @throws InterruptedException
  16. * if any thread has interrupted the current thread. The
  17. * <i>interrupted status</i> of the current thread is
  18. * cleared when this exception is thrown.
  19. */
  20. public final synchronized void join(long millis) throws InterruptedException {
  21. long base = System.currentTimeMillis();
  22. long now = 0;
  23. if (millis < 0) {
  24. throw new IllegalArgumentException("timeout value is negative");
  25. }
  26. //当millis为0时,说明后续线程需要被无限循环等待,直到当前线程结束运行
  27. if (millis == 0) {
  28. while (isAlive()) {
  29. wait(0);//wait的超时时间为0
  30. }
  31. } else {
  32. //当millis>0时,在millis毫秒内后续线程需要循环等待,直到超时当前线程自动死亡
  33. while (isAlive()) {
  34. long delay = millis - now;
  35. if (delay <= 0) {
  36. break;
  37. }
  38. wait(delay);//wait的超时时间为delay
  39. now = System.currentTimeMillis() - base;
  40. }
  41. }
  42. }
  43. /**
  44. * Thread类还提供一个等待时间为0的join方法
  45. * 用于将后续线程无限循环等待,直到当前线程结束运行
  46. */
  47. public final void join() throws InterruptedException {
  48. join(0);
  49. }
  • join()方法的使用
  1. Thread t1 = new Thread(new Runnable() {
  2. @Override
  3. public void run() {
  4. for (int i = 0;i<100;i++){
  5. System.out.println(Thread.currentThread().getName()+"线程值为:sally" + i); }
  6. }
  7. },"sally");
  8. Thread t2 = new Thread(new Runnable() {
  9. @Override
  10. public void run() {
  11. for (int i = 0;i<2;i++){
  12. System.out.println(Thread.currentThread().getName()+"线程值为:kira" + i);
  13. }
  14. }
  15. },"kira");
  16. t1.start();
  17. t1.join();//让t2线程和后续线程无限等待直到sally线程执行完毕
  18. t2.start();
  19. -------------
  20. //输出:
  21. ......
  22. sally线程值为:sally97
  23. sally线程值为:sally98
  24. sally线程值为:sally99
  25. kira线程值为:kira0 //可以发现直到sally线程执行完毕,kira线程才开始执行
  26. kira线程值为:kira1
  • join(long)方法的使用
  1. Thread t1 = new Thread(new Runnable() {
  2. @Override
  3. public void run() {
  4. try {
  5. System.out.println("beginTime=" + System.currentTimeMillis());
  6. Thread.sleep(5000);
  7. } catch (InterruptedException e) {
  8. e.printStackTrace();
  9. }
  10. }
  11. },"sally");
  12. t1.start();
  13. t1.join(2000);//当主线程等待2000毫秒
  14. System.out.println("endTime=" + System.currentTimeMillis());
  15. -------------
  16. //输出:
  17. ......
  18. beginTime=1502693592670
  19. endTime =1502693594670
  20. //endTime - beginTime = 2000 正好相当于等待的时间
  • join vs sleep
  • join(long)方法 在内部使用 wait(long)方法 进行等待,因此 join(long)方法 能够释放锁
  • Thread.sleep(long)方法 却不会释放锁
  • join vs synchronized
  • join()方法 在内部使用 wait()方法 进行等待
  • `synchronized 使用的是对象监视器原理作为同步

10.5 ThreadLocal

  • ThreadLocal
  • 变量共享:变量值的共享可以使用public static变量,所有线程都使用同一个静态变量
  • 作用: ThreadLocal 实现每个线程都有自己的共享变量,从而别的线程修改静态变量并不会对自身产生影响
  • 原理: ThreadLocal相当于全局存放数据的盒子,存储每个线程的私有数据
  • 重点: ThreadLocal 并不能解决并发带来的数据不一致问题,而主要用于备份共享变量作为私有变量
  • 补充:关于 ThreadLocal 请参见笔者的 并发番@ThreadLocal一文通,这里只是简单介绍
  • ThreadLocal的使用
  1. ThreadLocal threadLocal = new ThreadLocal();
  2. Thread t1 = new Thread(new Runnable() {
  3. @Override
  4. public void run() {
  5. for (int i = 0;i<2;i++){
  6. threadLocal.set("sally" + i);
  7. System.out.println(Thread.currentThread().getName() +
  8. "线程的ThreadLocal值为:" + threadLocal.get());
  9. }
  10. }
  11. },"sally");
  12. Thread t2 = new Thread(new Runnable() {
  13. @Override
  14. public void run() {
  15. for (int i = 0;i<2;i++){
  16. threadLocal.set("kira" + i);
  17. System.out.println(Thread.currentThread().getName() +
  18. "线程的ThreadLocal值为:" + threadLocal.get());
  19. }
  20. }
  21. },"kira");
  22. t1.start();
  23. t2.start();
  24. for (int i = 0;i<2;i++){
  25. threadLocal.set("Main" + i);
  26. System.out.println(Thread.currentThread().getName() +
  27. "线程的ThreadLocal值为:" + threadLocal.get());
  28. }
  29. //输出:
  30. main线程的ThreadLocal值为:Main0
  31. kira线程的ThreadLocal值为:kira0
  32. sally线程的ThreadLocal值为:sally0
  33. kira线程的ThreadLocal值为:kira1
  34. main线程的ThreadLocal值为:Main1
  35. sally线程的ThreadLocal值为:sally1

11.致谢

笔者完全是站在巨人们的肩膀之上艰难地完成本篇,即并发番的第一篇,对大神们的崇拜之意更加虔诚。文章肯定会有很多不足,希望看官们多多指导,同时笔者会定期维护之前的文章,力争做到完善和精益求精。为了完成此篇,笔者通读了大量的材料,以下为笔者推荐的并发相关的书籍,同时也是笔者作为参考的重要依据:

  • 《Java编程思想(第四版)》Bruce Eckel著
  • 《Java多线程编程核心技术》 高洪岩著
  • 《Java并发编程核心技术》 方腾飞、魏鹏、程晓明著
  • 《Java并发编程实践》 Brian Goetz、Tim Pieerls、Doug Lea、David Holmes等著
  • 《深入理解Java虚拟机》 周志明著
  • 《Java并发编程核心方法与框架》 高洪岩著
  • 《实战Java高并发程序设计》 葛一鸣 郭超著
  • 《Java7并发编程实战手册》 Javier Fernadez Gonzalez著
  • 《Java8 函数式编程》 Richard Warburton著

有空笔者搞个分享网盘,分享一下PDF、Visio、思维导图等相关资料