4.1 共享带来的问题

小故事

image.png
小男小女(线程)共用算盘(CPU),小南算加法,小女算减法,临时结果写到账本(内存),老王(操作系统)来调度两人使用。小王算到一半暂停(时间片用完),轮到小女使用,小女使用完写会结果。小男被唤醒继续算数,把1写到账本。
小男小女都觉得自己没做错,但笔记本里的结果是 1 而不是 0

Java 的体现

两个线程对初始值为 0 的静态变量一个做自增,一个做自减,各做 5000 次,结果是 0 吗?

  1. @Slf4j
  2. public class TestShare {
  3. static int counter = 0;
  4. public static void main(String[] args) throws InterruptedException {
  5. Thread t1 = new Thread(() -> {
  6. for (int i = 0; i < 5000; i++) {
  7. counter++;
  8. }
  9. }, "t1");
  10. Thread t2 = new Thread(() -> {
  11. for (int i = 0; i < 5000; i++) {
  12. counter--;
  13. }
  14. }, "t2");
  15. t1.start();
  16. t2.start();
  17. t1.join();
  18. t2.join();
  19. log.debug("{}",counter);
  20. }
  21. }

运行结果

  1. 09:53:27.002 [main] com.zhr.thread.TestShare - 461

问题分析
以上的结果可能是正数、负数、零。为什么呢?因为 Java 中对静态变量的自增,自减并不是原子操作,要彻底理解,必须从字节码来进行分析
例如对于 i++ 而言(i 为静态变量),实际会产生如下的 JVM 字节码指令:

  1. getstatic i // 获取静态变量i的值
  2. iconst_1 // 准备常量1
  3. iadd // 自增
  4. putstatic i // 将修改后的值存入静态变量i

而对应 i— 也是类似:

  1. getstatic i // 获取静态变量i的值
  2. iconst_1 // 准备常量1
  3. isub // 自减
  4. putstatic i // 将修改后的值存入静态变量i

而 Java 的内存模型如下,完成静态变量的自增,自减需要在主存和工作内存中进行数据交换:
image.png
如果是单线程以上 8 行代码是顺序执行(不会交错)没有问题,但多线程下这 8 行代码可能交错运行:
出现负数的情况如下图,若线程12顺序交换则为正数,若一个线程已经执行putstatic ,则结果是0
image.png

临界区 Critical Section

  • 一个程序运行多个线程本身是没有问题的
  • 问题出在多个线程访问共享资源
    • 多个线程读共享资源其实也没有问题
    • 在多个线程对共享资源读写操作时发生指令交错,就会出现问题
  • 一段代码块内如果存在对共享资源多线程读写操作,称这段代码块为临界区

例如,下面代码中的临界区

  1. static int counter = 0;
  2. static void increment() {
  3. // 临界区
  4. counter++;
  5. }
  6. static void decrement() {
  7. // 临界区
  8. counter--;
  9. }

竞态条件 Race Condition

多个线程在临界区内执行,由于代码的执行序列不同而导致结果无法预测,称之为发生了竞态条件

4.2 synchronized

* 应用之互斥

为了避免临界区的竞态条件发生,有多种手段可以达到目的。

  • 阻塞式的解决方案:synchronized,Lock
  • 非阻塞式的解决方案:原子变量

本次课使用阻塞式的解决方案:synchronized,来解决上述问题,即俗称的【对象锁】,它采用互斥的方式让同一
时刻至多只有一个线程能持有【对象锁】,其它线程再想获取这个【对象锁】时就会阻塞住。这样就能保证拥有锁
的线程可以安全的执行临界区内的代码,不用担心线程上下文切换

注意 虽然 java 中互斥和同步都可以采用 synchronized 关键字来完成,但它们还是有区别的:

  • 互斥是保证临界区的竞态条件发生,同一时刻只能有一个线程执行临界区代码
  • 同步是由于线程执行的先后、顺序不同、需要一个线程等待其它线程运行到某个点

synchronized 语法1

  1. synchronized(对象) // 线程1, 线程2(blocked)
  2. {
  3. 临界区
  4. }

解决问题

  1. @Slf4j
  2. public class TestShare1 {
  3. static int counter = 0;
  4. //static final Object room = new Object();
  5. public static void main(String[] args) throws InterruptedException {
  6. System.out.println();
  7. Thread t1 = new Thread(() -> {
  8. for (int i = 0; i < 5000; i++) {
  9. synchronized (TestShare1.class){
  10. counter++;
  11. }
  12. }
  13. }, "t1");
  14. Thread t2 = new Thread(() -> {
  15. for (int i = 0; i < 5000; i++) {
  16. synchronized (TestShare1.class){
  17. counter--;
  18. }
  19. }
  20. }, "t2");
  21. t1.start();
  22. t2.start();
  23. t1.join();
  24. t2.join();
  25. log.debug("{}",counter);
  26. }
  27. }

你可以做这样的类比:
image.png

  • synchronized(对象) 中的对象,可以想象为一个房间(room),有唯一入口(门)房间只能一次进入一人进行计算,线程 t1,t2 想象成两个人
  • 当线程 t1 执行到 synchronized(room)时就好比 t1 进入了这个房间,并锁住了门拿走了钥匙,在门内执行count++代码
  • 这时候如果 t2 也运行到了``synchronized(room)时,它发现门被锁住了,只能在门外等待,发生了上下文切换,阻塞住了
  • 这中间即使 t1 的 cpu 时间片不幸用完,被踢出了门外(不要错误理解为锁住了对象就能一直执行下去哦),这时门还是锁住的,t1 仍拿着钥匙,t2 线程还在阻塞状态进不来,只有下次轮到 t1 自己再次获得时间片时才能开门进入
  • 当 t1 执行完 synchronized{} 块内的代码,这时候才会从 obj 房间出来并解开门上的锁,唤醒 t2 线程把钥匙给他。t2 线程这时才可以进入 obj 房间,锁住了门拿上钥匙,执行它的 count--代码

图解
image.png

思考

synchronized 实际是用对象锁保证了临界区内代码的原子性,临界区内的代码对外是不可分割的,不会被线程切
换所打断。
为了加深理解,请思考下面的问题如果把 synchronized(obj) 放在 for 循环的外面,如何理解?— 原子性
结果正常,相当于整个for循环
如果 t1 synchronized(obj1) 而 t2 synchronized(obj2) 会怎样运作?— 锁对象
结果不正常,不是同一把锁
如果 t1 synchronized(obj) 而 t2 没有加会怎么样?如何理解?— 锁对象
结果不正常,t2能继续访问

面向对象的改进

  1. @Slf4j
  2. public class TestSynchronized {
  3. int value = 0;
  4. public void increment() {
  5. synchronized (this) {
  6. value++;
  7. }
  8. }
  9. public void decrement() {
  10. synchronized (this) {
  11. value--;
  12. }
  13. }
  14. public int get() {
  15. //确保读取到的值不是中间值
  16. synchronized (this) {
  17. return value;
  18. }
  19. }
  20. public static void main(String[] args) throws InterruptedException {
  21. TestSynchronized room = new TestSynchronized();
  22. Thread t1 = new Thread(() -> {
  23. for (int j = 0; j < 5000; j++) {
  24. room.increment();
  25. }
  26. }, "t1");
  27. Thread t2 = new Thread(() -> {
  28. for (int j = 0; j < 5000; j++) {
  29. room.decrement();
  30. }
  31. }, "t2");
  32. t1.start();
  33. t2.start();
  34. t1.join();
  35. t2.join();
  36. log.debug("count: {}", room.get());
  37. }
  38. }

4.3 方法上的 synchronized

  1. class Test{
  2. public synchronized void test() {
  3. }
  4. }

等价于

  1. class Test{
  2. public void test() {
  3. synchronized(this) {
  4. }
  5. }
  6. }
  1. class Test{
  2. public synchronized static void test() {
  3. }
  4. }

等价于

  1. class Test{
  2. public static void test() {
  3. synchronized(Test.class) {
  4. }
  5. }
  6. }

不加 synchronized 的方法
不加 synchronzied 的方法就好比不遵守规则的人,不去老实排队(好比翻窗户进去的)

线程八锁

所谓的“线程八锁”其实就是考察 synchronized 锁住的是哪个对象

  1. /**1
  2. * 结果 n1 n2 或者 n2 n1
  3. * 竞争同一个对象
  4. *
  5. * @author zhr
  6. * @date 2021/1/18 13:55
  7. **/
  8. @Slf4j
  9. public class 线程八锁_1 {
  10. public static void main(String[] args) {
  11. Number number = new Number();
  12. new Thread(() -> number.n1()).start();
  13. new Thread(() -> number.n2()).start();
  14. }
  15. }
  16. @Slf4j
  17. class Number {
  18. public synchronized void n1() {
  19. log.info("n1");
  20. }
  21. public synchronized void n2() {
  22. log.info("n2");
  23. }
  24. }
  1. /**2
  2. * 1S 后 n1 n2或者 n2 1S后n1
  3. * 竞争同一个对象
  4. *
  5. * @author zhr
  6. * @date 2021/1/18 13:55
  7. **/
  8. @Slf4j
  9. public class 线程八锁_2 {
  10. public static void main(String[] args) {
  11. Number2 number = new Number2();
  12. new Thread(() -> number.n1()).start();
  13. new Thread(() -> number.n2()).start();
  14. }
  15. }
  16. @Slf4j
  17. class Number2 {
  18. public synchronized void n1() {
  19. try {
  20. TimeUnit.SECONDS.sleep(1);
  21. } catch (InterruptedException e) {
  22. e.printStackTrace();
  23. }
  24. log.info("n1");
  25. }
  26. public synchronized void n2() {
  27. log.info("n2");
  28. }
  29. }
  1. /**3
  2. * n3 一秒后 n1 n2
  3. * n3 n2 一秒后n1
  4. * n2 n3 一秒后n1
  5. * n3 不参与锁竞争 n1n2 竞争同一个对象
  6. *
  7. * @author zhr
  8. * @date 2021/1/18 13:55
  9. **/
  10. @Slf4j
  11. public class 线程八锁_3 {
  12. public static void main(String[] args) {
  13. Number3 number = new Number3();
  14. new Thread(() -> number.n1()).start();
  15. new Thread(() -> number.n2()).start();
  16. new Thread(() -> number.n3()).start();
  17. }
  18. }
  19. @Slf4j
  20. class Number3 {
  21. public synchronized void n1() {
  22. try {
  23. TimeUnit.SECONDS.sleep(1);
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. }
  27. log.info("n1");
  28. }
  29. public synchronized void n2() {
  30. log.info("n2");
  31. }
  32. public void n3() {
  33. log.info("n3");
  34. }
  35. }
  1. /**4
  2. * n2 n1
  3. * 两个对象 无竞争
  4. *
  5. * @author zhr
  6. * @date 2021/1/18 13:55
  7. **/
  8. @Slf4j
  9. public class 线程八锁_4 {
  10. public static void main(String[] args) {
  11. Number4 number = new Number4();
  12. Number4 number1 = new Number4();
  13. new Thread(() -> number.n1()).start();
  14. new Thread(() -> number1.n2()).start();
  15. }
  16. }
  17. @Slf4j
  18. class Number4 {
  19. public synchronized void n1() {
  20. try {
  21. TimeUnit.SECONDS.sleep(1);
  22. } catch (InterruptedException e) {
  23. e.printStackTrace();
  24. }
  25. log.info("n1");
  26. }
  27. public synchronized void n2() {
  28. log.info("n2");
  29. }
  30. }
  1. /**5
  2. * n2 n1
  3. * n1 线程的锁是类对象 n2 的锁是number这个对象
  4. *
  5. * @author zhr
  6. * @date 2021/1/18 13:55
  7. **/
  8. @Slf4j
  9. public class 线程八锁_5 {
  10. public static void main(String[] args) {
  11. Number5 number = new Number5();
  12. new Thread(() -> number.n1()).start();
  13. new Thread(() -> number.n2()).start();
  14. }
  15. }
  16. @Slf4j
  17. class Number5 {
  18. public static synchronized void n1() {
  19. try {
  20. TimeUnit.SECONDS.sleep(1);
  21. } catch (InterruptedException e) {
  22. e.printStackTrace();
  23. }
  24. log.info("n1");
  25. }
  26. public synchronized void n2() {
  27. log.info("n2");
  28. }
  29. }
  1. /**6
  2. * 1S 后 n1 n2或者 n2 1S后n1
  3. * 存在竞争 竞争的是这个类对象
  4. *
  5. * @author zhr
  6. * @date 2021/1/18 13:55
  7. **/
  8. @Slf4j
  9. public class 线程八锁_6 {
  10. public static void main(String[] args) {
  11. Number6 number6 = new Number6();
  12. new Thread(() -> number6.n1()).start();
  13. new Thread(() -> number6.n2()).start();
  14. }
  15. }
  16. @Slf4j
  17. class Number6 {
  18. public static synchronized void n1() {
  19. try {
  20. TimeUnit.SECONDS.sleep(1);
  21. } catch (InterruptedException e) {
  22. e.printStackTrace();
  23. }
  24. log.info("n1");
  25. }
  26. public static synchronized void n2() {
  27. log.info("n2");
  28. }
  29. }
  1. /**7
  2. * n2 1S n1
  3. * 不存在竞争 n1线程锁是类对象 n2 线程锁是实例number2
  4. *
  5. * @author zhr
  6. * @date 2021/1/18 13:55
  7. **/
  8. @Slf4j
  9. public class 线程八锁_7 {
  10. public static void main(String[] args) {
  11. Number7 number1 = new Number7();
  12. Number7 number2 = new Number7();
  13. new Thread(() -> number1.n1()).start();
  14. new Thread(() -> number2.n2()).start();
  15. }
  16. }
  17. @Slf4j
  18. class Number7 {
  19. public static synchronized void n1() {
  20. try {
  21. TimeUnit.SECONDS.sleep(1);
  22. } catch (InterruptedException e) {
  23. e.printStackTrace();
  24. }
  25. log.info("n1");
  26. }
  27. public synchronized void n2() {
  28. log.info("n2");
  29. }
  30. }
  1. /**8
  2. * 1s 后12, 或 2 1s后 1
  3. * 存在竞争,竞争的是同一个类对象
  4. *
  5. * @author zhr
  6. * @date 2021/1/18 13:55
  7. **/
  8. @Slf4j
  9. public class 线程八锁_8 {
  10. public static void main(String[] args) {
  11. Number8 number1 = new Number8();
  12. Number8 number2 = new Number8();
  13. new Thread(() -> number1.n1()).start();
  14. new Thread(() -> number2.n2()).start();
  15. }
  16. }
  17. @Slf4j
  18. class Number8 {
  19. public static synchronized void n1() {
  20. try {
  21. TimeUnit.SECONDS.sleep(1);
  22. } catch (InterruptedException e) {
  23. e.printStackTrace();
  24. }
  25. log.info("n1");
  26. }
  27. public static synchronized void n2() {
  28. log.info("n2");
  29. }
  30. }

4.4 变量的线程安全分析

成员变量和静态变量是否线程安全?

  • 如果它们没有共享,则线程安全
  • 如果它们被共享了,根据它们的状态是否能够改变,又分两种情况

    • 如果只有读操作,则线程安全
    • 如果有读写操作,则这段代码是临界区,需要考虑线程安全

      局部变量是否线程安全?

  • 局部变量是线程安全的

  • 但局部变量引用的对象则未必
    • 如果该对象没有逃离方法的作用访问,它是线程安全的
    • 如果该对象逃离方法的作用范围,需要考虑线程安全

      局部变量线程安全分析

      1. public static void test1() {
      2. int i = 10;
      3. i++;
      4. }
      每个线程调用 test1() 方法时局部变量 i,会在每个线程的栈帧内存中被创建多份,因此不存在共享
      1. public static void test1();
      2. descriptor: ()V
      3. flags: ACC_PUBLIC, ACC_STATIC
      4. Code:
      5. stack=1, locals=1, args_size=0
      6. 0: bipush 10
      7. 2: istore_0
      8. 3: iinc 0, 1
      9. 6: return
      10. LineNumberTable:
      11. line 5: 0
      12. line 6: 3
      13. line 7: 6
      14. LocalVariableTable:
      15. Start Length Slot Name Signature
      16. 3 4 0 i I
      如图
      image.png

局部变量的引用稍有不同
先看一个成员变量的例子

  1. class ThreadUnsafe {
  2. ArrayList<String> list = new ArrayList<>();
  3. public void method1(int loopNumber) {
  4. for (int i = 0; i < loopNumber; i++) {
  5. // { 临界区, 会产生竞态条件
  6. method2();
  7. method3();
  8. // } 临界区
  9. }
  10. }
  11. private void method2() {
  12. list.add("1");
  13. }
  14. private void method3() {
  15. list.remove(0);
  16. }
  17. public static void main(String[] args) {
  18. ThreadUnsafe test = new ThreadUnsafe();
  19. //创建 2 个线程 每个线程执行 200 次
  20. for (int i = 0; i < 2; i++) {
  21. new Thread(() -> test.method1(200), "Thread" + i).start();
  22. }
  23. }
  24. }

运行结果,可能正常也可能报错

  1. Exception in thread "Thread1" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
  2. at java.util.ArrayList.rangeCheck(ArrayList.java:657)
  3. at java.util.ArrayList.remove(ArrayList.java:496)
  4. at com.zhr.thread.ThreadUnsafe.method3(ThreadUnsafe.java:19)
  5. at com.zhr.thread.ThreadUnsafe.method1(ThreadUnsafe.java:11)
  6. at com.zhr.thread.ThreadUnsafe.lambda$main$0(ThreadUnsafe.java:28)
  7. at java.lang.Thread.run(Thread.java:748)

分析:
无论哪个线程中的 method2 引用的都是同一个对象中的 list 成员变量
method3 与 method2 分析相同
image.png
将 list 修改为局部变量那么就不会有上述问题了

  1. class ThreadUnsafe1 {
  2. public void method1(int loopNumber) {
  3. ArrayList<String> list = new ArrayList<>();
  4. for (int i = 0; i < loopNumber; i++) {
  5. // { 临界区, 会产生竞态条件
  6. method2(list);
  7. method3(list);
  8. // } 临界区
  9. }
  10. }
  11. private void method2(ArrayList<String> list) {
  12. list.add("1");
  13. }
  14. private void method3(ArrayList<String> list) {
  15. list.remove(0);
  16. }
  17. public static void main(String[] args) {
  18. ThreadUnsafe1 test = new ThreadUnsafe1();
  19. //创建 2 个线程 每个线程执行 200 次
  20. for (int i = 0; i < 2; i++) {
  21. new Thread(() -> test.method1(200), "Thread" + i).start();
  22. }
  23. }
  24. }

分析:
list 是局部变量,每个线程调用时会创建其不同实例,没有共享
而 method2 的参数是从 method1 中传递过来的,与 method1 中引用同一个对象
method3 的参数分析与 method2 相同
image.png

方法访问修饰符带来的思考,如果把 method2 和 method3 的方法修改为 public 会不会代理线程安全问题?
情况1:有其它线程调用 method2 和 method3
情况2:在 情况1 的基础上,为 ThreadSafe 类添加子类,子类覆盖 method2 或 method3 方法,即

  1. class ThreadSafe {
  2. public final void method1(int loopNumber) {
  3. ArrayList<String> list = new ArrayList<>();
  4. for (int i = 0; i < loopNumber; i++) {
  5. method2(list);
  6. method3(list);
  7. }
  8. }
  9. public void method2(ArrayList<String> list) {
  10. list.add("1");
  11. }
  12. public void method3(ArrayList<String> list) {
  13. list.remove(0);
  14. }
  15. }
  16. class ThreadSafeSubClass extends ThreadSafe {
  17. @Override
  18. public void method3(ArrayList<String> list) {
  19. new Thread(() -> list.remove(0)).start();
  20. }
  21. }

从这个例子可以看出 private 或 fifinal 提供【安全】的意义所在,请体会开闭原则中的【闭】

常见线程安全类

String
Integer
StringBuffffer
Random
Vector
Hashtable
java.util.concurrent 包下的类
这里说它们是线程安全的是指,多个线程调用它们同一个实例的某个方法时,是线程安全的。也可以理解为

  1. Hashtable table = new Hashtable();
  2. new Thread(()-> table.put("key", "value1")).start();
  3. new Thread(()-> table.put("key", "value2")).start();

线程安全类方法的组合

它们的每个方法是原子的,但注意它们多个方法的组合不是原子的,见后面分析
分析下面代码是否线程安全?

  1. Hashtable table = new Hashtable();
  2. // 线程1,线程2
  3. if( table.get("key") == null) {
  4. table.put("key", value);
  5. }

image.png
不可变类线程安全性
String、Integer 等都是不可变类,因为其内部的状态不可以改变,因此它们的方法都是线程安全的
有同学或许有疑问,String 有 replace,substring 等方法【可以】改变值啊,那么这些方法又是如何保证线程安
全的呢?

  1. public class Immutable{
  2. private int value = 0;
  3. public Immutable(int value){
  4. this.value = value;
  5. }
  6. public int getValue(){
  7. return this.value;
  8. }
  9. }

如果想增加一个增加的方法呢?

  1. public class Immutable{
  2. private int value = 0;
  3. public Immutable(int value){
  4. this.value = value;
  5. }
  6. public int getValue(){
  7. return this.value;
  8. }
  9. public Immutable add(int v){
  10. return new Immutable(this.value + v);
  11. }
  12. }

实例分析

例1:

  1. //运行在Tomcat容器中,只有一个实例,会被tomcat的多个线程共享使用
  2. public class MyServlet extends HttpServlet {
  3. // 是否安全? 线程不安全,key,value可以修改,多个线程读写会发生混乱
  4. Map<String,Object> map = new HashMap<>();
  5. // 是否安全? 线程安全,属性不可修改
  6. String S1 = "...";
  7. // 是否安全? 线程安全,属性不可修改
  8. final String S2 = "...";
  9. // 是否安全? 线程不安全,会被共享,属性可修改
  10. Date D1 = new Date();
  11. // 是否安全? 线程不安全,引用不能变,但是属性可修改
  12. final Date D2 = new Date();
  13. public void doGet(HttpServletRequest request, HttpServletResponse response) {
  14. // 使用上述变量
  15. }
  16. }

例2:

  1. public class MyServlet extends HttpServlet {
  2. // 是否安全? 存在线程安全问题
  3. private UserService userService = new UserServiceImpl();
  4. public void doGet(HttpServletRequest request, HttpServletResponse response) {
  5. userService.update(...);
  6. }
  7. }
  8. public class UserServiceImpl implements UserService {
  9. // 记录调用次数 不安全
  10. private int count = 0;
  11. public void update() {
  12. // ...
  13. count++;
  14. }
  15. }

例3:

  1. @Aspect
  2. @Component
  3. //Spring 容器实例默认是单例,会被多个线程共享,可以换成环绕通知
  4. public class MyAspect {
  5. // 是否安全? 不安全
  6. private long start = 0L;
  7. @Before("execution(* *(..))")
  8. public void before() {
  9. start = System.nanoTime();
  10. }
  11. @After("execution(* *(..))")
  12. public void after() {
  13. long end = System.nanoTime();
  14. System.out.println("cost time:" + (end-start));
  15. }
  16. }

例4:

  1. public class MyServlet extends HttpServlet {
  2. // 是否安全 是 私有的,不可变
  3. private UserService userService = new UserServiceImpl();
  4. public void doGet(HttpServletRequest request, HttpServletResponse response) {
  5. userService.update(...);
  6. }
  7. }
  8. public class UserServiceImpl implements UserService {
  9. // 是否安全 是,无成员变量
  10. private UserDao userDao = new UserDaoImpl();
  11. public void update() {
  12. userDao.update();
  13. }
  14. }
  15. //没有成员变量,线程安全
  16. public class UserDaoImpl implements UserDao {
  17. public void update() {
  18. String sql = "update user set password = ? where username = ?";
  19. // 是否安全 安全,局部变量
  20. try (Connection conn = DriverManager.getConnection("","","")){
  21. // ...
  22. } catch (Exception e) {
  23. // ...
  24. }
  25. }
  26. }

例5:

  1. public class MyServlet extends HttpServlet {
  2. // 是否安全 否
  3. private UserService userService = new UserServiceImpl();
  4. public void doGet(HttpServletRequest request, HttpServletResponse response) {
  5. userService.update(...);
  6. }
  7. }
  8. public class UserServiceImpl implements UserService {
  9. // 是否安全 否
  10. private UserDao userDao = new UserDaoImpl();
  11. public void update() {
  12. userDao.update();
  13. }
  14. }
  15. public class UserDaoImpl implements UserDao {
  16. // 是否安全 不安全
  17. private Connection conn = null;
  18. public void update() throws SQLException {
  19. String sql = "update user set password = ? where username = ?";
  20. conn = DriverManager.getConnection("","","");
  21. // ...
  22. conn.close();
  23. }
  24. }

例6:

  1. public class MyServlet extends HttpServlet {
  2. // 是否安全
  3. private UserService userService = new UserServiceImpl();
  4. public void doGet(HttpServletRequest request, HttpServletResponse response) {
  5. userService.update(...);
  6. }
  7. }
  8. public class UserServiceImpl implements UserService {
  9. public void update() {
  10. UserDao userDao = new UserDaoImpl();
  11. userDao.update();
  12. }
  13. }
  14. public class UserDaoImpl implements UserDao {
  15. // 是否安全 线程安全,但不推荐这种写法
  16. private Connection conn = null;
  17. public void update() throws SQLException {
  18. String sql = "update user set password = ? where username = ?";
  19. conn = DriverManager.getConnection("","","");
  20. // ...
  21. conn.close();
  22. }
  23. }

例7:

  1. public abstract class Test {
  2. public void bar() {
  3. // 是否安全 SimpleDateFormat本身不是线程安全的
  4. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  5. foo(sdf);
  6. }
  7. //foo 方法被继承,从而可能被修改造成线程不安全
  8. public abstract foo(SimpleDateFormat sdf);
  9. public static void main(String[] args) {
  10. new Test().bar();
  11. }
  12. }

其中 foo 的行为是不确定的,可能导致不安全的发生,被称之为外星方法

  1. public void foo(SimpleDateFormat sdf) {
  2. String dateStr = "1999-10-11 00:00:00";
  3. for (int i = 0; i < 20; i++) {
  4. new Thread(() -> {
  5. try {
  6. sdf.parse(dateStr);
  7. } catch (ParseException e) {
  8. e.printStackTrace();
  9. }
  10. }).start();
  11. }
  12. }

请比较 JDK 中 String 类的实现
String 为什么是final 类的原因之一就是 防止被子类继承后状态被修改,造成线程不安全,体现了闭合原则

例8: 线程不安全

  1. @Slf4j
  2. public class TestConcurrent {
  3. private static Integer i = 0;
  4. private final static Object o = 0;
  5. public static void main(String[] args) {
  6. List<Thread> list = new ArrayList<>();
  7. for (int j = 0; j < 2; j++) {
  8. Thread thread = new Thread(() -> {
  9. for (int k = 0; k < 5000; k++) {
  10. synchronized (i) {
  11. i++;
  12. }
  13. }
  14. }, "" + j);
  15. list.add(thread);
  16. }
  17. list.stream().forEach(t -> t.start());
  18. list.stream().forEach(t -> {
  19. try {
  20. t.join();
  21. } catch (InterruptedException e) {
  22. e.printStackTrace();
  23. }
  24. });
  25. log.debug("{}", i);
  26. }
  27. }

4.5 习题

卖票练习

  1. //模拟卖票
  2. public class TestSell {
  3. public static void main(String[] args) throws InterruptedException {
  4. //模拟多人买票
  5. TicketWindow window = new TicketWindow(2000);
  6. //卖出的票数统计,线程安全
  7. List<Integer> soldAmount = new Vector<>();
  8. //买票人数
  9. List<Thread> threads = new ArrayList<>();
  10. for (int i = 0; i < 5000; i++) {
  11. Thread thread = new Thread(() -> {
  12. int sell = window.sell(Tools.getTicket());
  13. soldAmount.add(sell);
  14. });
  15. threads.add(thread);
  16. thread.start();
  17. }
  18. //等待所有线程执行完毕
  19. for (Thread thread : threads) {
  20. thread.join();
  21. }
  22. System.out.println("余票:" + window.getCount());
  23. System.out.println("卖出:" + soldAmount.stream().mapToInt(i -> i).sum());
  24. }
  25. }
  26. //售票窗口
  27. class TicketWindow {
  28. private int count;
  29. public TicketWindow(int count) {
  30. this.count = count;
  31. }
  32. //获取余票数量
  33. public int getCount() {
  34. return count;
  35. }
  36. //售票
  37. public synchronized int sell(int amount) {
  38. if (this.count >= amount) {
  39. this.count = this.count - amount;
  40. return amount;
  41. } else {
  42. return 0;
  43. }
  44. }
  45. }

将上述代码打包成可运行jar

  1. <plugin>
  2. <groupId>org.apache.maven.plugins</groupId>
  3. <artifactId>maven-shade-plugin</artifactId>
  4. <version>2.4.1</version>
  5. <executions>
  6. <execution>
  7. <phase>package</phase>
  8. <goals>
  9. <goal>shade</goal>
  10. </goals>
  11. <configuration>
  12. <transformers>
  13. <transformer
  14. implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
  15. <mainClass>com.zhr.TestSell</mainClass>
  16. </transformer>
  17. </transformers>
  18. </configuration>
  19. </execution>
  20. </executions>
  21. </plugin>

使用windows脚本多次运行

  1. for /L %n in (1,1,10) do java -jar codeforpackage-1.0.0.jar

售票方法不加synchronized关键字,运行结果

  1. F:\DOCUMENTS\IDEAProjects\java-study\codeforpackage\target>java -jar codeforpackage-1.0.0.jar
  2. 08:20:41.605 [main] INFO com.zhr.TestSell - 余票:0
  3. 08:20:41.620 [main] INFO com.zhr.TestSell - 卖出:2004
  4. F:\DOCUMENTS\IDEAProjects\java-study\codeforpackage\target>java -jar codeforpackage-1.0.0.jar
  5. 08:20:42.641 [main] INFO com.zhr.TestSell - 余票:0
  6. 08:20:42.656 [main] INFO com.zhr.TestSell - 卖出:2002

加synchronized关键字之后则OK

转账练习

  1. public class 转账 {
  2. public static void main(String[] args) throws InterruptedException {
  3. Account a = new Account(1000);
  4. Account b = new Account(1000);
  5. Thread thread1 = new Thread(() -> {
  6. for (int i = 0; i < 10; i++) {
  7. a.transfer(b, Tools.get(100));
  8. }
  9. }, "aaa");
  10. Thread thread2 = new Thread(() -> {
  11. for (int i = 0; i < 10; i++) {
  12. b.transfer(a, Tools.get(100));
  13. }
  14. }, "bbb");
  15. thread1.start();
  16. thread2.start();
  17. thread1.join();
  18. thread2.join();
  19. System.out.println("当前总额:" + (a.getMoney() + b.getMoney()));
  20. }
  21. }
  22. class Account {
  23. private int money;
  24. public Account(int money) {
  25. this.money = money;
  26. }
  27. public int getMoney() {
  28. return money;
  29. }
  30. public void setMoney(int money) {
  31. this.money = money;
  32. }
  33. public void transfer(Account target, int amount) {
  34. //效率低,是一个简单的解决方法
  35. synchronized (Account.class) {
  36. if (this.money >= amount) {
  37. this.setMoney(this.getMoney() - amount);
  38. target.setMoney(target.getMoney() + amount);
  39. }
  40. }
  41. }
  42. }

4.6 Monitor 概念

Java 对象头

32 位虚拟机
普通对象

Object Header (64 bits)
Mark Word (32 bits) Klass Word (32 bits)

Klass Word 指向对象所从属的class
数组对象

Object Header (96 bits)
Mark Word(32bits) Klass Word(32bits) array length(32bits)

其中 Mark Word 结构为

Mark Word (32 bits) State
hashcode:25 age:4 biased_lock:0 01 Normal
thread:23 epoch:2 age:4 biased_lock:1 01 Biased
ptr_to_lock_record:30 00 Lightweight Locked
ptr_to_heavyweight_monitor:30 10 Heavyweight Locked
11 Marked for GC

hashcode hash码
age 垃圾回收时的分代年龄
biased_lock 偏向锁 是否启用了偏向锁 0没有启用偏向锁 1 启用了偏向锁
state 加锁状态

thread 偏向锁时的线程ID
epoch 批量重定向和批量撤销时使用

ptr_to_lock_record 指向栈帧中琐记录的指针
ptr_to_heavyweight_monitor 指向monitor对象的指针

64位虚拟机
java 8默认开启指针压缩 关闭前占96bit 关闭后占128bit(关闭,命令 -XX:-UseCompressedOops)

64 位虚拟机 Mark Word

Mark Word (64 bits) State
unused:25 hashcode:31 unused:1 age:4 biased_lock:0 01 Normal
thread:54 epoch:2 unused:1 age:4 biased_lock:1 01 Biased
ptr_to_lock_record:62 00 Lightweight Locked
ptr_to_heavyweight_monitor:62 10 Heavyweight Locked
11 Marked for GC

参考资料 https://stackoverflow.com/questions/26357186/what-is-in-java-object-header

Monitor(锁)原理

Monitor 被翻译为监视器管程
每个 Java 对象都可以关联一个 Monitor 对象,如果使用 synchronized 给对象上锁(重量级)之后,该对象头的Mark Word 中就被设置指向 Monitor 对象的指针
Monitor 结构如下
image.png
刚开始 Monitor 中 Owner 为 null
当 Thread-2 执行 synchronized(obj) 就会将 Monitor 的所有者 Owner 置为 Thread-2,Monitor中只能有一个 Owner
在 Thread-2 上锁的过程中,如果 Thread-3,Thread-4,Thread-5 也来执行 synchronized(obj),就会进入EntryList BLOCKED
Thread-2 执行完同步代码块的内容,然后唤醒 EntryList 中等待的线程来竞争锁,竞争的时是非公平的
图中 WaitSet 中的 Thread-0,Thread-1 是之前获得过锁,但条件不满足进入 WAITING 状态的线程,后面讲wait-notify 时会分析

注意: synchronized 必须是进入同一个对象的 monitor 才有上述的效果 不加 synchronized 的对象不会关联监视器,不遵从以上规则

synchronized原理

  1. static final Object lock = new Object();
  2. static int counter = 0;
  3. public static void main(String[] args) {
  4. synchronized (lock) {
  5. counter++;
  6. }
  7. }

对应字节码

  1. public static void main(java.lang.String[]);
  2. descriptor: ([Ljava/lang/String;)V
  3. flags: ACC_PUBLIC, ACC_STATIC
  4. Code:
  5. stack=2, locals=3, args_size=1
  6. 0: getstatic #2 // <- 获取lock引用 (synchronized开始)
  7. 3: dup // 复制一份
  8. 4: astore_1 // 复制的lock引用 -> 存储到slot 1 (便于解锁)
  9. 5: monitorenter // (对应synchronized关键字)将 lock对象 MarkWord 置为 Monitor 指针
  10. 6: getstatic #3 // Field counter:I // <- i
  11. 9: iconst_1 // 准备常数 1
  12. 10: iadd // +1
  13. 11: putstatic #3 // Field counter:I // -> i
  14. 14: aload_1 // <- lock引用(astore_1存储的lock引用)
  15. 15: monitorexit // 将 lock对象 MarkWord 重置, 唤醒 EntryList
  16. 16: goto 24
  17. 19: astore_2 // e -> slot 2
  18. 20: aload_1 // <- lock引用
  19. 21: monitorexit // 将 lock对象 MarkWord 重置, 唤醒 EntryList
  20. 22: aload_2 // <- slot 2 (e)
  21. 23: athrow // <- slot 2 (e)
  22. 24: return
  23. Exception table:
  24. from to target type
  25. 6 16 19 any
  26. 19 22 19 any
  27. LineNumberTable:
  28. line 7: 0
  29. line 8: 6
  30. line 9: 14
  31. line 10: 24
  32. LocalVariableTable:
  33. Start Length Slot Name Signature
  34. 0 25 0 args [Ljava/lang/String;
  35. StackMapTable: number_of_entries = 2
  36. frame_type = 255 /* full_frame */
  37. offset_delta = 19
  38. locals = [ class "[Ljava/lang/String;", class java/lang/Object ]
  39. stack = [ class java/lang/Throwable ]
  40. frame_type = 250 /* chop */
  41. offset_delta = 4

注意 方法级别的 synchronized 不会在字节码指令中有所体现

小故事

故事角色
老王 - JVM
小南 - 线程
小女 - 线程
房间 - 对象
房间门上 - 防盗锁 - Monitor
房间门上 - 小南书包 - 轻量级锁
房间门上 - 刻上小南大名 - 偏向锁
批量重刻名 - 一个类的偏向锁撤销到达 20 阈值
不能刻名字 - 批量撤销该类对象的偏向锁,设置该类不可偏向
小南要使用房间保证计算不被其它人干扰(原子性),最初,他用的是防盗锁,当上下文切换时,锁住门。这样,即使他离开了,别人也进不了门,他的工作就是安全的。
但是,很多情况下没人跟他来竞争房间的使用权。小女是要用房间,但使用的时间上是错开的,小南白天用,小女晚上用。每次上锁太麻烦了,有没有更简单的办法呢?
小南和小女商量了一下,约定不锁门了,而是谁用房间,谁把自己的书包挂在门口,但他们的书包样式都一样,因此每次进门前得翻翻书包,看课本是谁的,如果是自己的,那么就可以进门,这样省的上锁解锁了。万一书包不是自己的,那么就在门外等,并通知对方下次用锁门的方式。
后来,小女回老家了,很长一段时间都不会用这个房间。小南每次还是挂书包,翻书包,虽然比锁门省事了,但仍然觉得麻烦。
于是,小南干脆在门上刻上了自己的名字:【小南专属房间,其它人勿用】,下次来用房间时,只要名字还在,那么说明没人打扰,还是可以安全地使用房间。如果这期间有其它人要用这个房间,那么由使用者将小南刻的名字擦掉,升级为挂书包的方式。
同学们都放假回老家了,小南就膨胀了,在 20 个房间刻上了自己的名字,想进哪个进哪个。后来他自己放假回老家了,这时小女回来了(她也要用这些房间),结果就是得一个个地擦掉小南刻的名字,升级为挂书包的方式。老王觉得这成本有点高,提出了一种批量重刻名的方法,他让小女不用挂书包了,可以直接在门上刻上自己的名字
后来,刻名的现象越来越频繁,老王受不了了:算了,这些房间都不能刻名了,只能挂书包

1. 轻量级锁

轻量级锁的使用场景:如果一个对象虽然有多线程要加锁,但加锁的时间是错开的(也就是没有竞争),那么可以使用轻量级锁来优化。
轻量级锁对使用者是透明的,即语法仍然是 synchronized
假设有两个方法同步块,利用同一个对象加锁

  1. static final Object obj = new Object();
  2. public static void method1() {
  3. synchronized( obj ) {
  4. // 同步块 A
  5. method2();
  6. }
  7. }
  8. public static void method2() {
  9. synchronized( obj ) {
  10. // 同步块 B
  11. }
  12. }

创建锁记录(Lock Record)对象,每个线程的栈帧都会包含一个锁记录的结构,内部可以存储锁定对象的Mark Word
image.png
让锁记录中 Object reference 指向锁对象,并尝试用 cas 替换 Object 的 Mark Word,将 Mark Word 的值存入锁记录
image.png
如果 cas 替换成功,对象头中存储了 锁记录地址和状态 00 ,表示由该线程给对象加锁,这时图示如下
image.png
如果 cas 失败,有两种情况

  • 如果是其它线程已经持有了该 Object 的轻量级锁,这时表明有竞争,进入锁膨胀过程
  • 如果是自己执行了 synchronized 锁重入,那么再添加一条 Lock Record 作为重入的计数

image.png
当退出 synchronized 代码块(解锁时)如果有取值为 null 的锁记录,表示有重入,这时重置锁记录,表示重入计数减一
image.png
当退出 synchronized 代码块(解锁时)锁记录的值不为 null,这时使用 cas 将 Mark Word 的值恢复给对象头

  • 成功,则解锁成功
  • 失败,说明轻量级锁进行了锁膨胀或已经升级为重量级锁,进入重量级锁解锁流程

    2. 锁膨胀

    如果在尝试加轻量级锁的过程中,CAS 操作无法成功,这时一种情况就是有其它线程为此对象加上了轻量级锁(有竞争),这时需要进行锁膨胀,将轻量级锁变为重量级锁。

    1. static Object obj = new Object();
    2. public static void method1() {
    3. synchronized( obj ) {
    4. // 同步块
    5. }
    6. }

    当 Thread-1 进行轻量级加锁时,Thread-0 已经对该对象加了轻量级锁
    image.png
    这时 Thread-1 加轻量级锁失败,进入锁膨胀流程

  • 即为 Object 对象申请 Monitor 锁,让 Object 指向重量级锁地址

  • 然后自己进入 Monitor 的 EntryList BLOCKED

image.png
当 Thread-0 退出同步块解锁时,使用 cas 将 Mark Word 的值恢复给对象头,失败。这时会进入重量级解锁流程,即按照 Monitor 地址找到 Monitor 对象,设置 Owner 为 null,唤醒 EntryList 中 BLOCKED 线程

3. 自旋优化

重量级锁竞争的时候,还可以使用自旋来进行优化,如果当前线程自旋成功(即这时候持锁线程已经退出了同步块,释放了锁),这时当前线程就可以避免阻塞。
自旋重试成功的情况

线程1(core1上) 对象Mark 线程2(core2上)
- 10(重量锁) -
访问同步块,获取monitor 10(重量锁)量量锁指针 -
成功(加锁) 10(重量锁)重量锁指针 -
执行同步块 10(重量锁)重量锁指针
执行同步块 10(重量锁)重量锁指针 访问同步块,获取 monitor
执行同步块 10(重量锁)重量锁指针 自旋重试
执行完毕 10(重量锁)重量锁指针 自旋重试
成功(解锁) 01(无锁) 自旋重试
- 10(重量锁)重量锁指针 成功(加锁)
- 10(重量锁)重量锁指针 执行同步块
-

自旋重试失败的情况

线程1(core1上) 对象Mark 线程2(core2上)
- 10(重量锁) -
访问同步块,获取monitor 10(重量锁)量量锁指针 -
成功(加锁) 10(重量锁)重量锁指针 -
执行同步块 10(重量锁)重量锁指针
执行同步块 10(重量锁)重量锁指针 访问同步块,获取 monitor
执行同步块 10(重量锁)重量锁指针 自旋重试
执行同步块 10(重量锁)重量锁指针 自旋重试
执行同步块 10(重量锁)重量锁指针 自旋重试
执行同步块 10(重量锁)重量锁指针 阻塞
-

自旋会占用 CPU 时间,单核 CPU 自旋就是浪费,多核 CPU 自旋才能发挥优势。
在 Java 6 之后自旋锁是自适应的,比如对象刚刚的一次自旋操作成功过,那么认为这次自旋成功的可能性会高,就多自旋几次;反之,就少自旋甚至不自旋,总之,比较智能。
Java 7 之后不能控制是否开启自旋功能

4. 偏向锁

轻量级锁在没有竞争时(就自己这个线程),每次重入仍然需要执行 CAS 操作。
Java 6 中引入了偏向锁来做进一步优化:只有第一次使用 CAS 将线程 ID 设置到对象的 Mark Word 头,之后这个线程发现对象头线程 ID 是自己的就表示没有竞争,不用重新 CAS。以后只要不发生竞争,这个对象就归该线程所有
例如:

  1. static final Object obj = new Object();
  2. public static void m1() {
  3. synchronized (obj) {
  4. // 同步块 A
  5. m2();
  6. }
  7. }
  8. public static void m2() {
  9. synchronized (obj) {
  10. // 同步块 B
  11. m3();
  12. }
  13. }
  14. public static void m3() {
  15. synchronized (obj) {
  16. // 同步块 C
  17. }
  18. }

image.png
image.png
偏向状态
回忆一下对象头格式

Mark Word (64 bits) State
unused:25 hashcode:31 unused:1 age:4 biased_lock:0 01 Normal
thread:54 epoch:2 unused:1 age:4 biased_lock:1 01 Biased
ptr_to_lock_record:62 00 Lightweight Locked
ptr_to_heavyweight_monitor:62 10 Heavyweight Locked
11 Marked for GC

一个对象创建时:

  • 如果开启了偏向锁(默认开启),那么对象创建后,markword 值为 0x05 即最后 3 位为 101,这时它的thread、epoch、age 都为 0
  • 偏向锁是默认是延迟的,不会在程序启动时立即生效,如果想避免延迟,可以加 VM 参数 -XX:BiasedLockingStartupDelay=0 来禁用延迟
  • 如果没有开启偏向锁,那么对象创建后,markword 值为 0x01 即最后 3 位为 001,这时它的 hashcode、age 都为 0,第一次用到 hashcode 时才会赋值

1) 测试延迟特性
2) 测试偏向锁

  1. class Dog {}

利用 jol 第三方工具来查看对象头信息(注意这里我扩展了 jol 让它输出更为简洁 ??? 无源码写不出)

  1. <dependency>
  2. <groupId>org.openjdk.jol</groupId>
  3. <artifactId>jol-core</artifactId>
  4. <version>0.10</version>
  5. </dependency>
  1. /**
  2. * 添加虚拟机参数 -XX:BiasedLockingStartupDelay=0
  3. * 禁用偏向锁 -XX:-UseBiasedLocking
  4. */
  5. public static void main(String[] args) {
  6. Dog d = new Dog();
  7. ClassLayout classLayout = ClassLayout.parseInstance(d);
  8. new Thread(() -> {
  9. log.debug("synchronized 前");
  10. System.out.println(classLayout.toPrintableSimple(true));
  11. log.info(classLayout.toPrintable());
  12. synchronized (d) {
  13. log.debug("synchronized 中");
  14. //log.info(classLayout.toPrintable());
  15. // System.out.println(classLayout.toPrintableSimple(true));
  16. }
  17. log.debug("synchronized 后");
  18. //log.info(classLayout.toPrintable());
  19. System.out.println(classLayout.toPrintableSimple(true));
  20. }, "t1").start();
  21. }

输出

  1. 11:08:58.117 c.TestBiased [t1] - synchronized
  2. 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000101
  3. 11:08:58.121 c.TestBiased [t1] - synchronized
  4. 00000000 00000000 00000000 00000000 00011111 11101011 11010000 00000101
  5. 11:08:58.121 c.TestBiased [t1] - synchronized
  6. 00000000 00000000 00000000 00000000 00011111 11101011 11010000 00000101

注意 处于偏向锁的对象解锁后,线程 id 仍存储于对象头中 优先偏向锁,然后轻量级锁,最后重量级锁

3)测试禁用
在上面测试代码运行时在添加 VM 参数 -XX:-UseBiasedLocking 禁用偏向锁
输出

  1. 11:13:10.018 c.TestBiased [t1] - synchronized
  2. 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  3. 11:13:10.021 c.TestBiased [t1] - synchronized
  4. 00000000 00000000 00000000 00000000 00100000 00010100 11110011 10001000
  5. 11:13:10.021 c.TestBiased [t1] - synchronized
  6. 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001

4) 测试 hashCode
正常状态对象一开始是没有 hashCode 的,第一次调用才生成

撤销 - 调用对象 hashCode
调用了对象的 hashCode,但偏向锁的对象 MarkWord 中存储的是线程 id,如果调用 hashCode 会导致偏向锁被撤销
轻量级锁会在锁记录中记录 hashCode
重量级锁会在 Monitor 中记录 hashCode
偏向状态markword最多可以存储偏向线程ID再想存31位的hashcode已经没有位置,导致 调用 hashCode 会导致偏向锁被撤销
在调用 hashCode 后使用偏向锁,记得去掉 -XX:-UseBiasedLocking
输出

  1. 11:22:10.386 c.TestBiased [main] - 调用 hashCode:1778535015
  2. 11:22:10.391 c.TestBiased [t1] - synchronized
  3. 00000000 00000000 00000000 01101010 00000010 01001010 01100111 00000001
  4. 11:22:10.393 c.TestBiased [t1] - synchronized
  5. 00000000 00000000 00000000 00000000 00100000 11000011 11110011 01101000
  6. 11:22:10.393 c.TestBiased [t1] - synchronized
  7. 00000000 00000000 00000000 01101010 00000010 01001010 01100111 00000001

撤销 - 其它线程使用对象
当有其它线程使用偏向锁对象时,会将偏向锁升级为轻量级锁

  1. @Slf4j
  2. public class TestBais3 {
  3. private static void test2() throws InterruptedException {
  4. Dog d = new Dog();
  5. Thread t1 = new Thread(() -> {
  6. synchronized (d) {
  7. log.debug(ClassLayout.parseInstance(d).toPrintableSimple(true));
  8. }
  9. synchronized (TestBais3.class) {
  10. TestBais3.class.notify();
  11. }
  12. // 如果不用 wait/notify 使用 join 必须打开下面的注释
  13. // 因为:t1 线程不能结束,否则底层线程可能被 jvm 重用作为 t2 线程,底层线程 id 是一样的
  14. /*try {
  15. System.in.read();
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. }*/
  19. }, "t1");
  20. t1.start();
  21. Thread t2 = new Thread(() -> {
  22. synchronized (TestBais3.class) {
  23. try {
  24. TestBais3.class.wait();
  25. } catch (InterruptedException e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. log.debug(ClassLayout.parseInstance(d).toPrintableSimple(true));
  30. synchronized (d) {
  31. log.debug(ClassLayout.parseInstance(d).toPrintableSimple(true));
  32. }
  33. log.debug(ClassLayout.parseInstance(d).toPrintableSimple(true));
  34. }, "t2");
  35. t2.start();
  36. }
  37. }

输出

  1. [t1] - 00000000 00000000 00000000 00000000 00011111 01000001 00010000 00000101
  2. [t2] - 00000000 00000000 00000000 00000000 00011111 01000001 00010000 00000101
  3. [t2] - 00000000 00000000 00000000 00000000 00011111 10110101 11110000 01000000
  4. [t2] - 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001

撤销 - 调用 wait/notify
wait/notify 针对于重量级锁 所以会撤销偏向锁

  1. public static void main(String[] args) throws InterruptedException {
  2. Dog d = new Dog();
  3. Thread t1 = new Thread(() -> {
  4. log.debug(ClassLayout.parseInstance(d).toPrintableSimple(true));
  5. synchronized (d) {
  6. log.debug(ClassLayout.parseInstance(d).toPrintableSimple(true));
  7. try {
  8. d.wait();
  9. } catch (InterruptedException e) {
  10. e.printStackTrace();
  11. }
  12. log.debug(ClassLayout.parseInstance(d).toPrintableSimple(true));
  13. }
  14. }, "t1");
  15. t1.start();
  16. new Thread(() -> {
  17. try {
  18. Thread.sleep(6000);
  19. } catch (InterruptedException e) {
  20. e.printStackTrace();
  21. }
  22. synchronized (d) {
  23. log.debug("notify");
  24. d.notify();
  25. }
  26. }, "t2").start();
  27. }

输出

  1. [t1] - 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000101
  2. [t1] - 00000000 00000000 00000000 00000000 00011111 10110011 11111000 00000101
  3. [t2] - notify
  4. [t1] - 00000000 00000000 00000000 00000000 00011100 11010100 00001101 11001010

批量重偏向
如果对象虽然被多个线程访问,但没有竞争,这时偏向了线程 T1 的对象仍有机会重新偏向 T2,重偏向会重置对象
的 Thread ID
当撤销偏向锁阈值超过 20 次后,jvm 会这样觉得,我是不是偏向错了呢,于是会在给这些对象加锁时重新偏向至
加锁线程

  1. private static void test3() throws InterruptedException {
  2. Vector<Dog> list = new Vector<>();
  3. Thread t1 = new Thread(() -> {
  4. for (int i = 0; i < 30; i++) {
  5. Dog d = new Dog();
  6. list.add(d);
  7. synchronized (d) {
  8. log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
  9. }
  10. }
  11. synchronized (list) {
  12. list.notify();
  13. }
  14. }, "t1");
  15. t1.start();
  16. Thread t2 = new Thread(() -> {
  17. synchronized (list) {
  18. try {
  19. list.wait();
  20. } catch (InterruptedException e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. log.debug("===============> ");
  25. for (int i = 0; i < 30; i++) {
  26. Dog d = list.get(i);
  27. log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
  28. synchronized (d) {
  29. log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
  30. }
  31. log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
  32. }
  33. }, "t2");
  34. t2.start();
  35. }

输出

  1. [t1] - 0 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  2. [t1] - 1 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  3. [t1] - 2 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  4. [t1] - 3 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  5. [t1] - 4 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  6. [t1] - 5 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  7. [t1] - 6 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  8. [t1] - 7 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  9. [t1] - 8 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  10. [t1] - 9 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  11. [t1] - 10 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  12. [t1] - 11 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  13. [t1] - 12 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  14. [t1] - 13 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  15. [t1] - 14 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  16. [t1] - 15 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  17. [t1] - 16 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  18. [t1] - 17 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  19. [t1] - 18 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  20. [t1] - 19 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  21. [t1] - 20 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  22. [t1] - 21 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  23. [t1] - 22 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  24. [t1] - 23 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  25. [t1] - 24 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  26. [t1] - 25 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  27. [t1] - 26 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  28. [t1] - 27 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  29. [t1] - 28 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  30. [t1] - 29 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  31. [t2] - ===============>
  32. [t2] - 0 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  33. [t2] - 0 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  34. [t2] - 0 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  35. [t2] - 1 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  36. [t2] - 1 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  37. [t2] - 1 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  38. [t2] - 2 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  39. [t2] - 2 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  40. [t2] - 2 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  41. [t2] - 3 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  42. [t2] - 3 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  43. [t2] - 3 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  44. [t2] - 4 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  45. [t2] - 4 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  46. [t2] - 4 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  47. [t2] - 5 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  48. [t2] - 5 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  49. [t2] - 5 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  50. [t2] - 6 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  51. [t2] - 6 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  52. [t2] - 6 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  53. [t2] - 7 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  54. [t2] - 7 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  55. [t2] - 7 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  56. [t2] - 8 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  57. [t2] - 8 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  58. [t2] - 8 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  59. [t2] - 9 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  60. [t2] - 9 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  61. [t2] - 9 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  62. [t2] - 10 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  63. [t2] - 10 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  64. [t2] - 10 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  65. [t2] - 11 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  66. [t2] - 11 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  67. [t2] - 11 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  68. [t2] - 12 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  69. [t2] - 12 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  70. [t2] - 12 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  71. [t2] - 13 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  72. [t2] - 13 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  73. [t2] - 13 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  74. [t2] - 14 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  75. [t2] - 14 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  76. [t2] - 14 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  77. [t2] - 15 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  78. [t2] - 15 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  79. [t2] - 15 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  80. [t2] - 16 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  81. [t2] - 16 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  82. [t2] - 16 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  83. [t2] - 17 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  84. [t2] - 17 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  85. [t2] - 17 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  86. [t2] - 18 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  87. [t2] - 18 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000
  88. [t2] - 18 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
  89. [t2] - 19 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  90. [t2] - 19 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  91. [t2] - 19 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  92. [t2] - 20 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  93. [t2] - 20 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  94. [t2] - 20 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  95. [t2] - 21 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  96. [t2] - 21 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  97. [t2] - 21 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  98. [t2] - 22 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  99. [t2] - 22 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  100. [t2] - 22 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  101. [t2] - 23 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  102. [t2] - 23 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  103. [t2] - 23 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  104. [t2] - 24 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  105. [t2] - 24 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  106. [t2] - 24 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  107. [t2] - 25 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  108. [t2] - 25 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  109. [t2] - 25 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  110. [t2] - 26 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  111. [t2] - 26 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  112. [t2] - 26 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  113. [t2] - 27 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  114. [t2] - 27 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  115. [t2] - 27 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  116. [t2] - 28 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  117. [t2] - 28 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  118. [t2] - 28 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  119. [t2] - 29 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
  120. [t2] - 29 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
  121. [t2] - 29 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101

批量撤销
当撤销偏向锁阈值超过 40 次后,jvm 会这样觉得,自己确实偏向错了,根本就不该偏向。于是整个类的所有对象
都会变为不可偏向的,新建的对象也是不可偏向的

  1. static Thread t1, t2, t3;
  2. private static void test4() throws InterruptedException {
  3. Vector<Dog> list = new Vector<>();
  4. int loopNumber = 39;
  5. t1 = new Thread(() -> {
  6. for (int i = 0; i < loopNumber; i++) {
  7. Dog d = new Dog();
  8. list.add(d);
  9. synchronized (d) {
  10. log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
  11. }
  12. }
  13. LockSupport.unpark(t2);
  14. }, "t1");
  15. t1.start();
  16. t2 = new Thread(() -> {
  17. LockSupport.park();
  18. log.debug("===============> ");
  19. for (int i = 0; i < loopNumber; i++) {
  20. Dog d = list.get(i);
  21. log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
  22. synchronized (d) {
  23. log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
  24. }
  25. log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
  26. }
  27. LockSupport.unpark(t3);
  28. }, "t2");
  29. t2.start();
  30. t3 = new Thread(() -> {
  31. LockSupport.park();
  32. log.debug("===============> ");
  33. for (int i = 0; i < loopNumber; i++) {
  34. Dog d = list.get(i);
  35. log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
  36. synchronized (d) {
  37. log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
  38. }
  39. log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
  40. }
  41. }, "t3");
  42. t3.start();
  43. t3.join();
  44. log.debug(ClassLayout.parseInstance(new Dog()).toPrintableSimple(true));
  45. }

参考资料 https://github.com/farmerjohngit/myblog/issues/12 https://www.cnblogs.com/LemonFive/p/11246086.html https://www.cnblogs.com/LemonFive/p/11248248.html 偏向锁论文

5. 锁消除

锁消除

  1. @Fork(1)
  2. @BenchmarkMode(Mode.AverageTime)
  3. @Warmup(iterations = 3)
  4. @Measurement(iterations = 5)
  5. @OutputTimeUnit(TimeUnit.NANOSECONDS)
  6. public class MyBenchmark {
  7. static int x = 0;
  8. @Benchmark
  9. public void a() throws Exception {
  10. x++;
  11. }
  12. @Benchmark
  13. //两种结果非常接近
  14. //JIT 编译器对局部变量进行优化 把synchronized关键字去掉,进行锁消除优化
  15. //使用 -XX:-EliminateLocks 禁用该优化则会产生较大性能差异
  16. public void b() throws Exception {
  17. Object o = new Object();
  18. synchronized (o) {
  19. x++;
  20. }
  21. }
  22. }
  1. java -jar benchmarks.jar
  2. Benchmark Mode Samples Score Score error Units
  3. c.i.MyBenchmark.a avgt 5 1.542 0.056 ns/op
  4. c.i.MyBenchmark.b avgt 5 1.518 0.091 ns/op
  5. java -XX:-EliminateLocks -jar benchmarks.jar
  6. Benchmark Mode Samples Score Score error Units
  7. c.i.MyBenchmark.a avgt 5 1.507 0.108 ns/op
  8. c.i.MyBenchmark.b avgt 5 16.976 1.572 ns/op

锁粗化

对相同对象多次加锁,导致线程发生多次重入,可以使用锁粗化方式来优化,这不同于之前讲的细分锁的粒度。

4.7 wait notify

小故事 - 为什么需要 wait

由于条件不满足,小南不能继续进行计算
但小南如果一直占用着锁,其它人就得一直阻塞,效率太低
image.png
于是老王单开了一间休息室(调用 wait 方法),让小南到休息室(WaitSet)等着去了,但这时锁释放开,其它人可以由老王随机安排进屋
直到小M将烟送来,大叫一声 [ 你的烟到了 ] (调用 notify 方法)
image.png
小南于是可以离开休息室,重新进入竞争锁的队列
image.png

wait notify 原理

image.png
Owner 线程发现条件不满足,调用 wait 方法,即可进入 WaitSet 变为 WAITING 状态
BLOCKED 和 WAITING 的线程都处于阻塞状态,不占用 CPU 时间片
BLOCKED 线程会在 Owner 线程释放锁时唤醒
WAITING 线程会在 Owner 线程调用 notify 或 notifyAll 时唤醒,但唤醒后并不意味者立刻获得锁,仍需进入EntryList 重新竞争

API 介绍

obj.wait() 方法让进入 object 监视器的线程释放对象的锁,进入 WaitSet 等待区,从而让其他线程就机会获取对象的锁。无限制等待,直到notify 为止
obj.wait(long n) 有时限的等待, 到 n 毫秒后结束等待,或是被 notify
obj.notify() 在 object 上正在 waitSet 等待的线程中挑一个唤醒
obj.notifyAll() 让 object 上正在 waitSet 等待的线程全部唤醒
它们都是线程之间进行协作的手段,都属于 Object 对象的方法。必须获得此对象的锁,才能调用这几个方法

  1. @Slf4j
  2. public class TestWaitNotify {
  3. final static Object obj = new Object();
  4. public static void main(String[] args) throws InterruptedException {
  5. new Thread(() -> {
  6. synchronized (obj) {
  7. log.debug("执行....");
  8. try {
  9. obj.wait(); // 让线程在obj上一直等待下去
  10. } catch (InterruptedException e) {
  11. e.printStackTrace();
  12. }
  13. log.debug("其它代码....");
  14. }
  15. }).start();
  16. new Thread(() -> {
  17. synchronized (obj) {
  18. log.debug("执行....");
  19. try {
  20. obj.wait(); // 让线程在obj上一直等待下去
  21. } catch (InterruptedException e) {
  22. e.printStackTrace();
  23. }
  24. log.debug("其它代码....");
  25. }
  26. }).start();
  27. // 主线程两秒后执行
  28. TimeUnit.SECONDS.sleep(2);
  29. log.debug("唤醒 obj 上其它线程");
  30. synchronized (obj) {
  31. //obj.notify(); // 唤醒obj上一个线程
  32. obj.notifyAll(); // 唤醒obj上所有等待线程
  33. }
  34. }
  35. }

notify 的一种结果(程序没有停止运行)

  1. 16:11:33.196 [Thread-0] DEBUG com.zhr.thread.TestWaitNotify - 执行....
  2. 16:11:33.201 [Thread-1] DEBUG com.zhr.thread.TestWaitNotify - 执行....
  3. 16:11:35.193 [main] DEBUG com.zhr.thread.TestWaitNotify - 唤醒 obj 上其它线程
  4. 16:11:35.193 [Thread-0] DEBUG com.zhr.thread.TestWaitNotify - 其它代码....

notifyAll 的一种结果

  1. 16:01:21.711 [Thread-0] DEBUG com.zhr.thread.TestWaitNotify - 执行....
  2. 16:01:21.716 [Thread-1] DEBUG com.zhr.thread.TestWaitNotify - 执行....
  3. 16:01:23.712 [main] DEBUG com.zhr.thread.TestWaitNotify - 唤醒 obj 上其它线程
  4. 16:01:23.727 [Thread-1] DEBUG com.zhr.thread.TestWaitNotify - 其它代码....
  5. 16:01:23.728 [Thread-0] DEBUG com.zhr.thread.TestWaitNotify - 其它代码....

4.8 wait notify 的正确姿势

sleep(long n) 和 wait(long n) 的区别

1) sleep 是 Thread 方法,而 wait 是 Object 的方法
2) sleep 不需要强制和 synchronized 配合使用,但 wait 需要和 synchronized 一起用
3) sleep 在睡眠的同时,不会释放对象锁的,但 wait 在等待的时候会释放对象锁
4) 它们状态 TIMED_WAITING

step 1

  1. @Slf4j
  2. public class Test1 {
  3. static final Object room = new Object();
  4. static boolean hasCigarette = false;
  5. static boolean hasTakeout = false;
  6. public static void main(String[] args) {
  7. for (int i = 0; i < 5; i++) {
  8. new Thread(() -> {
  9. synchronized (room) {
  10. log.debug("可以开始干活了");
  11. }
  12. }, "其它人").start();
  13. }
  14. new Thread(() -> {
  15. synchronized (room) {
  16. log.debug("有烟没?[{}]", hasCigarette);
  17. if (!hasCigarette) {
  18. log.debug("没烟,先歇会!");
  19. sleep(2);
  20. }
  21. log.debug("有烟没?[{}]", hasCigarette);
  22. if (hasCigarette) {
  23. log.debug("可以开始干活了");
  24. }
  25. }
  26. }, "小南").start();
  27. sleep(1);
  28. new Thread(() -> {
  29. // 这里能不能加 synchronized (room)?
  30. hasCigarette = true;
  31. log.debug("烟到了噢!");
  32. }, "送烟的").start();
  33. }
  34. }

运行结果

  1. 16:46:18.650 [其它人] DEBUG com.zhr.thread.waitnotify.Test1 - 可以开始干活了
  2. 16:46:18.657 [小南] DEBUG com.zhr.thread.waitnotify.Test1 - 有烟没?[false]
  3. 16:46:18.660 [小南] DEBUG com.zhr.thread.waitnotify.Test1 - 没烟,先歇会!
  4. 16:46:19.643 [送烟的] DEBUG com.zhr.thread.waitnotify.Test1 - 烟到了噢!
  5. 16:46:20.664 [小南] DEBUG com.zhr.thread.waitnotify.Test1 - 有烟没?[true]
  6. 16:46:20.667 [小南] DEBUG com.zhr.thread.waitnotify.Test1 - 可以开始干活了
  7. 16:46:20.667 [其它人] DEBUG com.zhr.thread.waitnotify.Test1 - 可以开始干活了
  8. 16:46:20.667 [其它人] DEBUG com.zhr.thread.waitnotify.Test1 - 可以开始干活了
  9. 16:46:20.668 [其它人] DEBUG com.zhr.thread.waitnotify.Test1 - 可以开始干活了
  10. 16:46:20.670 [其它人] DEBUG com.zhr.thread.waitnotify.Test1 - 可以开始干活了

其它干活的线程,都要一直阻塞,效率太低
小南线程必须睡足 2s 后才能醒来,就算烟提前送到,也无法立刻醒来
加了 synchronized (room) 后,就好比小南在里面反锁了门睡觉,烟根本没法送进门,main 没加synchronized 就好像 main 线程是翻窗户进来的
解决方法,使用 wait - notify 机制

step 2

  1. @Slf4j
  2. public class Test2 {
  3. static final Object room = new Object();
  4. static boolean hasCigarette = false;
  5. static boolean hasTakeout = false;
  6. public static void main(String[] args) {
  7. new Thread(() -> {
  8. synchronized (room) {
  9. log.debug("有烟没?[{}]", hasCigarette);
  10. if (!hasCigarette) {
  11. log.debug("没烟,先歇会!");
  12. try {
  13. room.wait(2000);
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. log.debug("有烟没?[{}]", hasCigarette);
  19. if (hasCigarette) {
  20. log.debug("可以开始干活了");
  21. }
  22. }
  23. }, "小南").start();
  24. for (int i = 0; i < 5; i++) {
  25. new Thread(() -> {
  26. synchronized (room) {
  27. log.debug("可以开始干活了");
  28. }
  29. }, "其它人").start();
  30. }
  31. sleep(1);
  32. new Thread(() -> {
  33. synchronized (room) {
  34. hasCigarette = true;
  35. log.debug("烟到了噢!");
  36. room.notify();
  37. }
  38. }, "送烟的").start();
  39. }
  40. }

输出

  1. 16:55:49.519 [小南] DEBUG com.zhr.thread.waitnotify.Test2 - 有烟没?[false]
  2. 16:55:49.527 [小南] DEBUG com.zhr.thread.waitnotify.Test2 - 没烟,先歇会!
  3. 16:55:49.527 [其它人] DEBUG com.zhr.thread.waitnotify.Test2 - 可以开始干活了
  4. 16:55:49.528 [其它人] DEBUG com.zhr.thread.waitnotify.Test2 - 可以开始干活了
  5. 16:55:49.528 [其它人] DEBUG com.zhr.thread.waitnotify.Test2 - 可以开始干活了
  6. 16:55:49.528 [其它人] DEBUG com.zhr.thread.waitnotify.Test2 - 可以开始干活了
  7. 16:55:49.528 [其它人] DEBUG com.zhr.thread.waitnotify.Test2 - 可以开始干活了
  8. 16:55:50.518 [送烟的] DEBUG com.zhr.thread.waitnotify.Test2 - 烟到了噢!
  9. 16:55:50.518 [小南] DEBUG com.zhr.thread.waitnotify.Test2 - 有烟没?[true]
  10. 16:55:50.518 [小南] DEBUG com.zhr.thread.waitnotify.Test2 - 可以开始干活了

解决了其它干活的线程阻塞的问题
但如果有其它线程也在等待条件呢?

step 3

  1. @Slf4j
  2. public class Test3 {
  3. static final Object room = new Object();
  4. static boolean hasCigarette = false;
  5. static boolean hasTakeout = false;
  6. public static void main(String[] args) {
  7. new Thread(() -> {
  8. synchronized (room) {
  9. log.debug("有烟没?[{}]", hasCigarette);
  10. if (!hasCigarette) {
  11. log.debug("没烟,先歇会!");
  12. try {
  13. room.wait();
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. log.debug("有烟没?[{}]", hasCigarette);
  19. if (hasCigarette) {
  20. log.debug("可以开始干活了");
  21. } else {
  22. log.debug("没干成活...");
  23. }
  24. }
  25. }, "小南").start();
  26. new Thread(() -> {
  27. synchronized (room) {
  28. Thread thread = Thread.currentThread();
  29. log.debug("外卖送到没?[{}]", hasTakeout);
  30. if (!hasTakeout) {
  31. log.debug("没外卖,先歇会!");
  32. try {
  33. room.wait();
  34. } catch (InterruptedException e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. log.debug("外卖送到没?[{}]", hasTakeout);
  39. if (hasTakeout) {
  40. log.debug("可以开始干活了");
  41. } else {
  42. log.debug("没干成活...");
  43. }
  44. }
  45. }, "小女").start();
  46. sleep(1);
  47. new Thread(() -> {
  48. synchronized (room) {
  49. hasTakeout = true;
  50. log.debug("外卖到了噢!");
  51. room.notify();
  52. }
  53. }, "送外卖的").start();
  54. }
  55. }

输出

  1. 08:32:02.534 [小南] DEBUG com.zhr.thread.waitnotify.Test3 - 有烟没?[false]
  2. 08:32:02.539 [小南] DEBUG com.zhr.thread.waitnotify.Test3 - 没烟,先歇会!
  3. 08:32:02.539 [小女] DEBUG com.zhr.thread.waitnotify.Test3 - 外卖送到没?[false]
  4. 08:32:02.539 [小女] DEBUG com.zhr.thread.waitnotify.Test3 - 没外卖,先歇会!
  5. 08:32:03.534 [送外卖的] DEBUG com.zhr.thread.waitnotify.Test3 - 外卖到了噢!
  6. 08:32:03.535 [小南] DEBUG com.zhr.thread.waitnotify.Test3 - 有烟没?[false]
  7. 08:32:03.535 [小南] DEBUG com.zhr.thread.waitnotify.Test3 - 没干成活...

notify 只能随机唤醒一个 WaitSet 中的线程,这时如果有其它线程也在等待,那么就可能唤醒不了正确的线程,称之为【虚假唤醒】
解决方法,改为 notifyAll

step 4

  1. new Thread(() -> {
  2. synchronized (room) {
  3. hasTakeout = true;
  4. log.debug("外卖到了噢!");
  5. room.notifyAll();
  6. }
  7. }, "送外卖的").start();

输出

  1. 08:35:32.178 [小南] DEBUG com.zhr.thread.waitnotify.Test4 - 有烟没?[false]
  2. 08:35:32.184 [小南] DEBUG com.zhr.thread.waitnotify.Test4 - 没烟,先歇会!
  3. 08:35:32.184 [小女] DEBUG com.zhr.thread.waitnotify.Test4 - 外卖送到没?[false]
  4. 08:35:32.184 [小女] DEBUG com.zhr.thread.waitnotify.Test4 - 没外卖,先歇会!
  5. 08:35:33.179 [送外卖的] DEBUG com.zhr.thread.waitnotify.Test4 - 外卖到了噢!
  6. 08:35:33.179 [小女] DEBUG com.zhr.thread.waitnotify.Test4 - 外卖送到没?[true]
  7. 08:35:33.179 [小女] DEBUG com.zhr.thread.waitnotify.Test4 - 可以开始干活了
  8. 08:35:33.179 [小南] DEBUG com.zhr.thread.waitnotify.Test4 - 有烟没?[false]
  9. 08:35:33.179 [小南] DEBUG com.zhr.thread.waitnotify.Test4 - 没干成活...

用 notifyAll 仅解决某个线程的唤醒问题,但使用 if + wait 判断仅有一次机会,一旦条件不成立,就没有重新判断的机会了
解决方法,用 while + wait,当条件不成立,再次 wait

step 5

将 if 改为 while

  1. while (!hasCigarette) {
  2. log.debug("没烟,先歇会!");
  3. try {
  4. room.wait();
  5. } catch (InterruptedException e) {
  6. e.printStackTrace();
  7. }
  8. }

输出 (小南进入等待,不会立即退出,这样等到条件满足,可以继续运行)

  1. 13:38:18.285 [小南] DEBUG com.zhr.thread.waitnotify.Test5 - 有烟没?[false]
  2. 13:38:18.302 [小南] DEBUG com.zhr.thread.waitnotify.Test5 - 没烟,先歇会!
  3. 13:38:18.302 [小女] DEBUG com.zhr.thread.waitnotify.Test5 - 外卖送到没?[false]
  4. 13:38:18.302 [小女] DEBUG com.zhr.thread.waitnotify.Test5 - 没外卖,先歇会!
  5. 13:38:19.297 [送外卖的] DEBUG com.zhr.thread.waitnotify.Test5 - 外卖到了噢!
  6. 13:38:19.297 [小女] DEBUG com.zhr.thread.waitnotify.Test5 - 外卖送到没?[true]
  7. 13:38:19.297 [小女] DEBUG com.zhr.thread.waitnotify.Test5 - 可以开始干活了
  8. 13:38:19.298 [小南] DEBUG com.zhr.thread.waitnotify.Test5 - 没烟,先歇会!

总结

  1. synchronized(lock) {
  2. while(条件不成立) {
  3. lock.wait();
  4. }
  5. // 干活
  6. }
  7. //另一个线程
  8. synchronized(lock) {
  9. lock.notifyAll();
  10. }

* 模式之保护性暂停(Guarded Suspension)

1. 定义

即 Guarded Suspension,用在一个线程等待另一个线程的执行结果
要点

  • 有一个结果需要从一个线程传递到另一个线程,让他们关联同一个 GuardedObject
  • 如果有结果不断从一个线程到另一个线程那么可以使用消息队列(见生产者/消费者)
  • JDK 中,join 的实现、Future 的实现,采用的就是此模式
  • 因为要等待另一方的结果,因此归类到同步模式

image.png

2. 实现

  1. public class GuardedObject {
  2. private Object response;
  3. private final Object lock = new Object();
  4. public Object get() {
  5. synchronized (lock) {
  6. // 条件不满足则等待
  7. while (response == null) {
  8. try {
  9. lock.wait();
  10. } catch (InterruptedException e) {
  11. e.printStackTrace();
  12. }
  13. }
  14. return response;
  15. }
  16. }
  17. public void complete(Object response) {
  18. synchronized (lock) {
  19. // 条件满足,通知等待线程
  20. this.response = response;
  21. lock.notifyAll();
  22. }
  23. }
  24. }

* 应用

一个线程等待另一个线程的执行结果

  1. public static void main(String[] args) {
  2. GuardedObject guardedObject = new GuardedObject();
  3. new Thread(() -> {
  4. // 子线程执行下载
  5. List<String> response = download();
  6. log.debug("download complete...");
  7. guardedObject.complete(response);
  8. }).start();
  9. log.debug("waiting...");
  10. // 主线程阻塞等待
  11. Object response = guardedObject.get();
  12. log.debug("get response: [{}] lines", ((List<String>) response).size());
  13. }
  14. public static List<String> download() {
  15. List<String> data = new ArrayList<>();
  16. try {
  17. TimeUnit.SECONDS.sleep(3);
  18. } catch (InterruptedException e) {
  19. e.printStackTrace();
  20. }
  21. return data;
  22. }

运行结果

  1. 14:31:32.643 [main] DEBUG com.zhr.thread.guarded.GuardedObject - waiting...
  2. 14:31:35.641 [Thread-0] DEBUG com.zhr.thread.guarded.GuardedObject - download complete...
  3. 14:31:35.641 [main] DEBUG com.zhr.thread.guarded.GuardedObject - get response: [0] lines

3. 带超时版 GuardedObject

如果要控制超时时间呢

  1. @Slf4j
  2. public class GuardedObjectV2 {
  3. private Object response;
  4. private final Object lock = new Object();
  5. public Object get(long millis) {
  6. synchronized (lock) {
  7. // 1) 记录最初时间
  8. long begin = System.currentTimeMillis();
  9. // 2) 已经经历的时间
  10. long timePassed = 0;
  11. while (response == null) {
  12. // 4) 假设 millis 是 1000,结果在 400 时唤醒了,那么还有 600 要等
  13. long waitTime = millis - timePassed;
  14. log.debug("waitTime: {}", waitTime);
  15. if (waitTime <= 0) {
  16. log.debug("break...");
  17. break;
  18. }
  19. try {
  20. lock.wait(waitTime);
  21. } catch (InterruptedException e) {
  22. e.printStackTrace();
  23. }
  24. // 3) 如果提前被唤醒,这时已经经历的时间假设为 400
  25. timePassed = System.currentTimeMillis() - begin;
  26. log.debug("timePassed: {}, object is null {}",
  27. timePassed, response == null);
  28. }
  29. return response;
  30. }
  31. }
  32. public void complete(Object response) {
  33. synchronized (lock) {
  34. // 条件满足,通知等待线程
  35. this.response = response;
  36. log.debug("notify...");
  37. lock.notifyAll();
  38. }
  39. }
  40. public static void main(String[] args) {
  41. GuardedObjectV2 v2 = new GuardedObjectV2();
  42. new Thread(() -> {
  43. sleep(1);
  44. v2.complete(null);
  45. sleep(1);
  46. v2.complete(Arrays.asList("a", "b", "c"));
  47. }).start();
  48. Object response = v2.get(2500);
  49. if (response != null) {
  50. log.debug("get response: [{}] lines", ((List<String>) response).size());
  51. } else {
  52. log.debug("can't get response");
  53. }
  54. }
  55. }

运行结果

  1. 15:51:34.585 [main] DEBUG com.zhr.thread.guarded.GuardedObjectV2 - waitTime: 2500
  2. 15:51:35.586 [Thread-0] DEBUG com.zhr.thread.guarded.GuardedObjectV2 - notify...
  3. 15:51:35.586 [main] DEBUG com.zhr.thread.guarded.GuardedObjectV2 - timePassed: 1005, object is null true
  4. 15:51:35.586 [main] DEBUG com.zhr.thread.guarded.GuardedObjectV2 - waitTime: 1495
  5. 15:51:36.588 [Thread-0] DEBUG com.zhr.thread.guarded.GuardedObjectV2 - notify...
  6. 15:51:36.589 [main] DEBUG com.zhr.thread.guarded.GuardedObjectV2 - timePassed: 2008, object is null false
  7. 15:51:36.589 [main] DEBUG com.zhr.thread.guarded.GuardedObjectV2 - get response: [3] lines

等待超时

  1. Object response = v2.get(1500);

运行结果

  1. 15:52:28.774 [main] DEBUG com.zhr.thread.guarded.GuardedObjectV2 - waitTime: 1500
  2. 15:52:29.774 [Thread-0] DEBUG com.zhr.thread.guarded.GuardedObjectV2 - notify...
  3. 15:52:29.774 [main] DEBUG com.zhr.thread.guarded.GuardedObjectV2 - timePassed: 1004, object is null true
  4. 15:52:29.774 [main] DEBUG com.zhr.thread.guarded.GuardedObjectV2 - waitTime: 496
  5. 15:52:30.270 [main] DEBUG com.zhr.thread.guarded.GuardedObjectV2 - timePassed: 1500, object is null true
  6. 15:52:30.270 [main] DEBUG com.zhr.thread.guarded.GuardedObjectV2 - waitTime: 0
  7. 15:52:30.270 [main] DEBUG com.zhr.thread.guarded.GuardedObjectV2 - break...
  8. 15:52:30.270 [main] DEBUG com.zhr.thread.guarded.GuardedObjectV2 - can't get response
  9. 15:52:30.774 [Thread-0] DEBUG com.zhr.thread.guarded.GuardedObjectV2 - notify...

join 原理

是调用者轮询检查线程 alive 状态

  1. t1.join();

等价于下面的代码

  1. synchronized (t1) {
  2. // 调用者线程进入 t1 的 waitSet 等待, 直到 t1 运行结束
  3. while (t1.isAlive()) {
  4. t1.wait(0);
  5. }
  6. }

注意 join 体现的是【保护性暂停】模式,请参考之

jdk中join 的源码

  1. public final synchronized void join(long millis)
  2. throws InterruptedException {
  3. long base = System.currentTimeMillis();
  4. long now = 0;
  5. if (millis < 0) {
  6. throw new IllegalArgumentException("timeout value is negative");
  7. }
  8. if (millis == 0) {
  9. while (isAlive()) {
  10. wait(0);
  11. }
  12. } else {
  13. while (isAlive()) {
  14. long delay = millis - now;
  15. if (delay <= 0) {
  16. break;
  17. }
  18. wait(delay);
  19. now = System.currentTimeMillis() - base;
  20. }
  21. }
  22. }

4. 多任务版 GuardedObject

图中 Futures 就好比居民楼一层的信箱(每个信箱有房间编号),左侧的 t0,t2,t4 就好比等待邮件的居民,右侧的 t1,t3,t5 就好比邮递员
如果需要在多个类之间使用 GuardedObject 对象,作为参数传递不是很方便,因此设计一个用来解耦的中间类,这样不仅能够解耦【结果等待者】和【结果生产者】,还能够同时支持多个任务的管理
image.png
GuardedObject 对象

  1. @Slf4j
  2. public class GuardedObjectV3 {
  3. private Object response;
  4. private final Object lock = new Object();
  5. /**
  6. * 新增 id 用来标识 Guarded Object
  7. */
  8. private int id;
  9. public GuardedObjectV3(int id) {
  10. this.id = id;
  11. }
  12. public int getId() {
  13. return id;
  14. }
  15. public Object get(long millis) {
  16. synchronized (lock) {
  17. // 1) 记录最初时间
  18. long begin = System.currentTimeMillis();
  19. // 2) 已经经历的时间
  20. long timePassed = 0;
  21. while (response == null) {
  22. // 4) 假设 millis 是 1000,结果在 400 时唤醒了,那么还有 600 要等
  23. long waitTime = millis - timePassed;
  24. //log.debug("waitTime: {}", waitTime);
  25. if (waitTime <= 0) {
  26. //log.debug("break...");
  27. break;
  28. }
  29. try {
  30. lock.wait(waitTime);
  31. } catch (InterruptedException e) {
  32. e.printStackTrace();
  33. }
  34. // 3) 如果提前被唤醒,这时已经经历的时间假设为 400
  35. timePassed = System.currentTimeMillis() - begin;
  36. //log.debug("timePassed: {}, object is null {}", timePassed, response == null);
  37. }
  38. return response;
  39. }
  40. }
  41. public void complete(Object response) {
  42. synchronized (lock) {
  43. // 条件满足,通知等待线程
  44. this.response = response;
  45. //log.debug("notify...");
  46. lock.notifyAll();
  47. }
  48. }
  49. }

中间解耦类

  1. @Slf4j
  2. public class MailBoxes {
  3. private static Map<Integer, GuardedObjectV3> boxes = new Hashtable<>();
  4. private static int id = 1;
  5. /**
  6. * 产生唯一ID
  7. *
  8. * @return 唯一ID
  9. */
  10. private static synchronized int generateId() {
  11. return id++;
  12. }
  13. public static GuardedObjectV3 getGuardedObject(int id) {
  14. return boxes.remove(id);
  15. }
  16. public static GuardedObjectV3 createGuardedObject() {
  17. GuardedObjectV3 object = new GuardedObjectV3(generateId());
  18. boxes.put(object.getId(), object);
  19. return object;
  20. }
  21. public static Set<Integer> getIds() {
  22. return boxes.keySet();
  23. }
  24. }

业务相关类

  1. @Slf4j
  2. public class People extends Thread {
  3. @Override
  4. public void run() {
  5. //收信
  6. GuardedObjectV3 guardedObject = MailBoxes.createGuardedObject();
  7. log.info("开始收Id为{}的邮件", guardedObject.getId());
  8. Object mail = guardedObject.get(5000);
  9. log.info("收到Id为{}的邮件,内容是{}", guardedObject.getId(), mail);
  10. }
  11. }
  1. @Slf4j
  2. public class Postman extends Thread {
  3. private int id;
  4. private String mail;
  5. public Postman(int id, String mail) {
  6. this.id = id;
  7. this.mail = mail;
  8. }
  9. @Override
  10. public void run() {
  11. GuardedObjectV3 guardedObject = MailBoxes.getGuardedObject(id);
  12. log.info("送信开始id{}内容{}", id, mail);
  13. guardedObject.complete(mail);
  14. }
  15. }

测试类

  1. public class Test {
  2. public static void main(String[] args) throws InterruptedException {
  3. for (int i = 0; i < 3; i++) {
  4. new People().start();
  5. }
  6. TimeUnit.SECONDS.sleep(1);
  7. for (Integer id : MailBoxes.getIds()) {
  8. new Postman(id, "Hello " + id).start();
  9. }
  10. }
  11. }

某次运行结果

  1. 19:41:12.736 [Thread-0] INFO com.zhr.thread.guarded.multitask.People - 开始收Id3的邮件
  2. 19:41:13.731 [Thread-3] INFO com.zhr.thread.guarded.multitask.Postman - 送信开始id3内容Hello 3
  3. 19:41:13.731 [Thread-5] INFO com.zhr.thread.guarded.multitask.Postman - 送信开始id1内容Hello 1
  4. 19:41:13.731 [Thread-4] INFO com.zhr.thread.guarded.multitask.Postman - 送信开始id2内容Hello 2
  5. 19:41:13.731 [Thread-1] INFO com.zhr.thread.guarded.multitask.People - 收到Id1的邮件,内容是Hello 1
  6. 19:41:13.731 [Thread-2] INFO com.zhr.thread.guarded.multitask.People - 收到Id2的邮件,内容是Hello 2
  7. 19:41:13.732 [Thread-0] INFO com.zhr.thread.guarded.multitask.People - 收到Id3的邮件,内容是Hello 3

* 模式之生产者消费者

1. 定义

要点

  • 与前面的保护性暂停中的 GuardObject 不同,不需要产生结果和消费结果的线程一一对应
  • 消费队列可以用来平衡生产和消费的线程资源
  • 生产者仅负责产生结果数据,不关心数据该如何处理,而消费者专心处理结果数据
  • 消息队列是有容量限制的,满时不会再加入数据,空时不会再消耗数据
  • JDK 中各种阻塞队列,采用的就是这种模式

image.png
消息类

  1. /**
  2. * 自定义消息类 - 线程安全
  3. */
  4. public final class Message {
  5. /**
  6. * 消息ID
  7. */
  8. private int id;
  9. /**
  10. * 消息内容
  11. */
  12. private Object data;
  13. public Message(int id, Object data) {
  14. this.id = id;
  15. this.data = data;
  16. }
  17. public int getId() {
  18. return id;
  19. }
  20. public Object getData() {
  21. return data;
  22. }
  23. @Override
  24. public String toString() {
  25. return "Message{" +
  26. "id=" + id +
  27. ", data=" + data +
  28. '}';
  29. }
  30. }

消息队列类(线程间通讯)

  1. /**
  2. * 消息队列,线程之间进行通讯
  3. */
  4. @Slf4j
  5. public class MessageQueue {
  6. /**
  7. * 消息
  8. */
  9. private LinkedList<Message> list = new LinkedList<>();
  10. /**
  11. * 队列大小
  12. */
  13. private int capacity = 0;
  14. public MessageQueue(int capacity) {
  15. this.capacity = capacity;
  16. }
  17. /**
  18. * 添加消息
  19. */
  20. public void put(Message message) {
  21. synchronized (list) {
  22. while (list.size() == capacity) {
  23. try {
  24. log.info("消息队列已满,生产者等待...");
  25. list.wait();
  26. } catch (InterruptedException e) {
  27. e.printStackTrace();
  28. }
  29. }
  30. log.info("消息队列不满,生产者继续生产");
  31. list.addLast(message);
  32. list.notifyAll();
  33. }
  34. }
  35. /**
  36. * 获取消息
  37. */
  38. public Message take() {
  39. synchronized (list) {
  40. while (list.isEmpty()) {
  41. try {
  42. log.info("消息队列为空,消费者进入等待...");
  43. list.wait();
  44. } catch (InterruptedException e) {
  45. e.printStackTrace();
  46. }
  47. }
  48. log.info("消息队列中有消息,消费者继续消费");
  49. Message message = list.removeFirst();
  50. list.notifyAll();
  51. return message;
  52. }
  53. }
  54. }

测试类

  1. public class Test {
  2. public static void main(String[] args) {
  3. MessageQueue messageQueue = new MessageQueue(2);
  4. for (int i = 0; i < 3; i++) {
  5. int j = i;
  6. new Thread(() -> messageQueue.put(new Message(j, "消息" + j)), "生产者" + i).start();
  7. }
  8. new Thread(() -> {
  9. while (true) {
  10. try {
  11. TimeUnit.SECONDS.sleep(1);
  12. } catch (InterruptedException e) {
  13. e.printStackTrace();
  14. }
  15. Message take = messageQueue.take();
  16. }
  17. }, "消费者").start();
  18. }
  19. }

运行结果

  1. 20:31:14.136 [生产者0] INFO com.zhr.thread.guarded.providerandcustomer.MessageQueue - 消息队列不满,生产者继续生产
  2. 20:31:14.139 [生产者2] INFO com.zhr.thread.guarded.providerandcustomer.MessageQueue - 消息队列不满,生产者继续生产
  3. 20:31:14.139 [生产者1] INFO com.zhr.thread.guarded.providerandcustomer.MessageQueue - 消息队列已满,生产者等待...
  4. 20:31:15.134 [消费者] INFO com.zhr.thread.guarded.providerandcustomer.MessageQueue - 消息队列中有消息,消费者继续消费
  5. 20:31:15.134 [生产者1] INFO com.zhr.thread.guarded.providerandcustomer.MessageQueue - 消息队列不满,生产者继续生产
  6. 20:31:16.138 [消费者] INFO com.zhr.thread.guarded.providerandcustomer.MessageQueue - 消息队列中有消息,消费者继续消费
  7. 20:31:17.139 [消费者] INFO com.zhr.thread.guarded.providerandcustomer.MessageQueue - 消息队列中有消息,消费者继续消费
  8. 20:31:18.139 [消费者] INFO com.zhr.thread.guarded.providerandcustomer.MessageQueue - 消息队列为空,消费者进入等待...

4.9 Park & Unpark

基本使用

它们是 LockSupport 类中的方法

  1. // 暂停当前线程
  2. LockSupport.park();
  3. // 恢复某个线程的运行
  4. LockSupport.unpark(暂停线程对象)

先 park 再 unpark

  1. @Slf4j
  2. public class Test {
  3. public static void main(String[] args) {
  4. Thread t1 = new Thread(() -> {
  5. log.debug("start...");
  6. sleep(1);
  7. log.debug("park...");
  8. LockSupport.park();
  9. log.debug("resume...");
  10. }, "t1");
  11. t1.start();
  12. sleep(2);
  13. log.debug("unpark...");
  14. LockSupport.unpark(t1);
  15. }
  16. }

运行结果

  1. 20:42:02.579 [t1] DEBUG com.zhr.thread.parkunpark.Test - start...
  2. 20:42:03.586 [t1] DEBUG com.zhr.thread.parkunpark.Test - park...
  3. 20:42:04.582 [main] DEBUG com.zhr.thread.parkunpark.Test - unpark...
  4. 20:42:04.582 [t1] DEBUG com.zhr.thread.parkunpark.Test - resume...

先 unpark 再 park

  1. @Slf4j
  2. public class Test {
  3. public static void main(String[] args) {
  4. Thread t1 = new Thread(() -> {
  5. log.debug("start...");
  6. sleep(3);
  7. log.debug("park...");
  8. LockSupport.park();
  9. log.debug("resume...");
  10. }, "t1");
  11. t1.start();
  12. sleep(1);
  13. log.debug("unpark...");
  14. LockSupport.unpark(t1);
  15. }
  16. }

运行结果

  1. 20:43:53.825 [t1] DEBUG com.zhr.thread.parkunpark.Test - start...
  2. 20:43:54.824 [main] DEBUG com.zhr.thread.parkunpark.Test - unpark...
  3. 20:43:56.831 [t1] DEBUG com.zhr.thread.parkunpark.Test - park...
  4. 20:43:56.831 [t1] DEBUG com.zhr.thread.parkunpark.Test - resume...

特点

与 Object 的 wait & notify 相比

  • wait,notify 和 notifyAll 必须配合 Object Monitor 一起使用,而 park,unpark 不必
  • park & unpark 是以线程为单位来【阻塞】和【唤醒】线程,而 notify 只能随机唤醒一个等待线程,notifyAll是唤醒所有等待线程,就不那么【精确】
  • park & unpark 可以先 unpark,而 wait & notify 不能先 notify

    park unpark 原理

    每个线程都有自己的一个 Parker 对象,由三部分组成 _counter_cond_mutex打个比喻

  • 线程就像一个旅人,Parker 就像他随身携带的背包,条件变量就好比背包中的帐篷。_counter 就好比背包中的备用干粮(0 为耗尽,1 为充足)

  • 调用 park 就是要看需不需要停下来歇息
    • 如果备用干粮耗尽,那么钻进帐篷歇息
    • 如果备用干粮充足,那么不需停留,继续前进
  • 调用 unpark,就好比令干粮充足
    • 如果这时线程还在帐篷,就唤醒让他继续前进
    • 如果这时线程还在运行,那么下次他调用 park 时,仅是消耗掉备用干粮,不需停留继续前进
      • 因为背包空间有限,多次调用 unpark 仅会补充一份备用干粮

image.png

  1. 当前线程调用 Unsafe.park() 方法
    2. 检查 _counter ,本情况为 0,这时,获得 _mutex 互斥锁
    3. 线程进入 _cond 条件变量阻塞
    4. 设置 _counter = 0

image.png
1. 调用 Unsafe.unpark(Thread_0) 方法,设置 _counter 为 1
2. 唤醒 _cond 条件变量中的 Thread_0
3. Thread_0 恢复运行
4. 设置 _counter 为 0
image.png
1. 调用 Unsafe.unpark(Thread_0) 方法,设置 _counter 为 1
2. 当前线程调用 Unsafe.park() 方法
3. 检查 _counter ,本情况为 1,这时线程无需阻塞,继续运行
4. 设置 _counter 为 0

4.10 重新理解线程状态转换

image.png
假设有线程 Thread t

情况 1 NEW —> RUNNABLE

当调用t.start() 方法时,由 NEW —> RUNNABLE

情况 2 RUNNABLE <—> WAITING

t线程用 synchronized(obj) 获取了对象锁后

  • 调用 obj.wait() 方法时,t 线程从 RUNNABLE —> WAITING
  • 调用 obj.notify() , obj.notifyAll() , t.interrupt() 时

    • 竞争锁成功,t 线程从 WAITING —> RUNNABLE
    • 竞争锁失败,t 线程从 WAITING —> BLOCKED

      1. @Slf4j
      2. public class TestWaitNotify1 {
      3. final static Object obj = new Object();
      4. public static void main(String[] args) {
      5. new Thread(() -> {
      6. synchronized (obj) {
      7. log.debug("执行....");
      8. try {
      9. obj.wait();
      10. } catch (InterruptedException e) {
      11. e.printStackTrace();
      12. }
      13. log.debug("其它代码...."); // 断点
      14. }
      15. }, "t1").start();
      16. new Thread(() -> {
      17. synchronized (obj) {
      18. log.debug("执行....");
      19. try {
      20. obj.wait();
      21. } catch (InterruptedException e) {
      22. e.printStackTrace();
      23. }
      24. log.debug("其它代码...."); // 断点
      25. }
      26. }, "t2").start();
      27. sleep(1);
      28. log.debug("唤醒 obj 上其它线程");
      29. synchronized (obj) {
      30. obj.notifyAll(); // 唤醒obj上所有等待线程 断点
      31. }
      32. }
      33. }

      情况 3 RUNNABLE <—> WAITING

      当前线程调用 t.join() 方法时,当前线程从 RUNNABLE —> WAITING
      注意是当前线程在t 线程对象的监视器上等待
      t 线程运行结束,或调用了当前线程的 interrupt() 时,当前线程从 WAITING —> RUNNABLE

      情况 4 RUNNABLE <—> WAITING

      当前线程调用 LockSupport.park() 方法会让当前线程从 RUNNABLE —> WAITING
      调用 LockSupport.unpark(目标线程) 或调用了线程 的 interrupt() ,会让目标线程从 WAITING —>RUNNABLE

      情况 5 RUNNABLE <—> TIMED_WAITING

      t 线程用 synchronized(obj) 获取了对象锁后

  • 调用 obj.wait(long n) 方法时,t 线程从 RUNNABLE —> TIMED_WAITING

  • t 线程等待时间超过了 n 毫秒,或调用 obj.notify() , obj.notifyAll() , t.interrupt() 时

    • 竞争锁成功,t 线程从 TIMED_WAITING —> RUNNABLE
    • 竞争锁失败,t 线程从 TIMED_WAITING —> BLOCKED

      情况 6 RUNNABLE <—> TIMED_WAITING

      当前线程调用 t.join(long n) 方法时,当前线程从 RUNNABLE —> TIMED_WAITING
      注意是当前线程在t 线程对象的监视器上等待
      当前线程等待时间超过了 n 毫秒,或t 线程运行结束,或调用了当前线程的 interrupt() 时,当前线程从
      TIMED_WAITING —> RUNNABLE

      情况 7 RUNNABLE <—> TIMED_WAITING

      当前线程调用 Thread.sleep(long n) ,当前线程从 RUNNABLE —> TIMED_WAITING
      当前线程等待时间超过了 n 毫秒,当前线程从 TIMED_WAITING —> RUNNABLE

      情况 8 RUNNABLE <—> TIMED_WAITING

      当前线程调用 LockSupport.parkNanos(long nanos) 或 LockSupport.parkUntil(long millis) 时,当前线程从 RUNNABLE —> TIMED_WAITING
      调用 LockSupport.unpark(目标线程) 或调用了线程 的 interrupt() ,或是等待超时,会让目标线程从TIMED_WAITING—> RUNNABLE

      情况 9 RUNNABLE <—> BLOCKED

      t 线程用 synchronized(obj) 获取了对象锁时如果竞争失败,从 RUNNABLE —> BLOCKED
      持 obj 锁线程的同步代码块执行完毕,会唤醒该对象上所有 BLOCKED 的线程重新竞争,如果其中 t 线程竞争成功,从 BLOCKED —> RUNNABLE ,其它失败的线程仍然 BLOCKED情况 10 RUNNABLE <—> TERMINATED
      当前线程所有代码运行完毕,进入 TERMINATED

      4.11 多把锁

      多把不相干的锁
      一间大屋子有两个功能:睡觉、学习,互不相干。
      现在小南要学习,小女要睡觉,但如果只用一间屋子(一个对象锁)的话,那么并发度很低
      解决方法是准备多个房间(多个对象锁)
      例如

      1. @Slf4j
      2. public class BigRoom1 {
      3. public void work() {
      4. synchronized (this) {
      5. log.debug("working 2 小时");
      6. sleep(2);
      7. }
      8. }
      9. public void study() {
      10. synchronized (this) {
      11. log.debug("study 1 小时");
      12. sleep(1);
      13. }
      14. }
      15. }

      执行

      1. BigRoom1 bigRoom = new BigRoom1();
      2. new Thread(() -> bigRoom.study(), "小南").start();
      3. new Thread(() -> bigRoom.work(), "小女").start();

      某次运行结果

      1. 08:40:56.427 [小南] DEBUG com.zhr.thread.multilock.BigRoom1 - study 1 小时
      2. 08:40:57.433 [小女] DEBUG com.zhr.thread.multilock.BigRoom1 - working 2 小时

      改进

      1. @Slf4j
      2. public class BigRoom2 {
      3. private final Object studyRoom = new Object();
      4. private final Object workRoom = new Object();
      5. public void work() {
      6. synchronized (workRoom) {
      7. log.debug("working 2 小时");
      8. sleep(2);
      9. }
      10. }
      11. public void study() {
      12. synchronized (studyRoom) {
      13. log.debug("study 1 小时");
      14. sleep(1);
      15. }
      16. }
      17. public static void main(String[] args) {
      18. BigRoom2 bigRoom = new BigRoom2();
      19. new Thread(() -> bigRoom.study(), "小南").start();
      20. new Thread(() -> bigRoom.work(), "小女").start();
      21. }
      22. }

      某次执行结果

      1. 08:42:28.664 [小女] DEBUG com.zhr.thread.multilock.BigRoom2 - working 2 小时
      2. 08:42:28.651 [小南] DEBUG com.zhr.thread.multilock.BigRoom2 - study 1 小时

      将锁的粒度细分

  • 好处,是可以增强并发度

  • 坏处,如果一个线程需要同时获得多把锁,就容易发生死锁

4.12 活跃性

死锁

有这样的情况:一个线程需要同时获取多把锁,这时就容易发生死锁
t1 线程 获得 A对象 锁,接下来想获取 B对象 的锁 t2 线程 获得 B对象 锁,接下来想获取 A对象 的锁 例:

  1. Object A = new Object();
  2. Object B = new Object();
  3. Thread t1 = new Thread(() -> {
  4. synchronized (A) {
  5. log.debug("lock A");
  6. sleep(1);
  7. synchronized (B) {
  8. log.debug("lock B");
  9. log.debug("操作...");
  10. }
  11. }
  12. }, "t1");
  13. Thread t2 = new Thread(() -> {
  14. synchronized (B) {
  15. log.debug("lock B");
  16. sleep(0.5);
  17. synchronized (A) {
  18. log.debug("lock A");log.debug("操作...");
  19. }
  20. }
  21. }, "t2");
  22. t1.start();
  23. t2.start();

结果

定位死锁

检测死锁可以使用 jconsole工具,或者:

使用jstack定位

使用 jps 定位进程 id,再用 jstack 定位死锁

  1. jps
  2. 13920
  3. 5908 JConsole
  4. 21260 Jps
  5. 6764 TestDeadLock
  1. ...
  2. Java stack information for the threads listed above:
  3. ===================================================
  4. "t2":
  5. at com.zhr.thread.deadlock.TestDeadLock.lambda$main$1(TestDeadLock.java:27)
  6. - waiting to lock <0x00000000d7d85ca0> (a java.lang.Object)
  7. - locked <0x00000000d7d85cb0> (a java.lang.Object)
  8. at com.zhr.thread.deadlock.TestDeadLock$$Lambda$2/410424423.run(Unknown Source)
  9. at java.lang.Thread.run(Thread.java:748)
  10. "t1":
  11. at com.zhr.thread.deadlock.TestDeadLock.lambda$main$0(TestDeadLock.java:17)
  12. - waiting to lock <0x00000000d7d85cb0> (a java.lang.Object)
  13. - locked <0x00000000d7d85ca0> (a java.lang.Object)
  14. at com.zhr.thread.deadlock.TestDeadLock$$Lambda$1/1030870354.run(Unknown Source)
  15. at java.lang.Thread.run(Thread.java:748)
  16. Found 1 deadlock.
  17. ...

使用 jconsole工具

线程面板 选择 检测死锁
image.png
查看死锁信息
image.png

避免死锁要注意加锁顺序

另外如果由于某个线程进入了死循环,导致其它线程一直等待,对于这种情况 linux 下可以通过 top 先定位到
CPU 占用高的 Java 进程,再利用 top -Hp 进程id 来定位是哪个线程,最后再用 jstack 排查

哲学家就餐问题

image.png
有五位哲学家,围坐在圆桌旁。

  • 他们只做两件事,思考和吃饭,思考一会吃口饭,吃完饭后接着思考。
  • 吃饭时要用两根筷子吃,桌上共有 5 根筷子,每位哲学家左右手边各有一根筷子。
  • 如果筷子被身边的人拿着,自己就得等待

筷子类

  1. class Chopstick {
  2. String name;
  3. public Chopstick(String name) {
  4. this.name = name;
  5. }
  6. @Override
  7. public String toString() {
  8. return "筷子{" + name + '}';
  9. }
  10. }

哲学家类

  1. @Slf4j
  2. class Philosopher extends Thread {
  3. Chopstick left;
  4. Chopstick right;
  5. public Philosopher(String name, Chopstick left, Chopstick right) {
  6. super(name);
  7. this.left = left;
  8. this.right = right;
  9. }
  10. private void eat() {
  11. log.debug("eating...");
  12. Utils.sleep(1);
  13. }
  14. @Override
  15. public void run() {
  16. while (true) {
  17. // 获得左手筷子
  18. synchronized (left) {
  19. // 获得右手筷子
  20. synchronized (right) {
  21. // 吃饭
  22. eat();
  23. }
  24. // 放下右手筷子
  25. }
  26. // 放下左手筷子
  27. }
  28. }
  29. }

就餐

  1. Chopstick c1 = new Chopstick("1");
  2. Chopstick c2 = new Chopstick("2");
  3. Chopstick c3 = new Chopstick("3");
  4. Chopstick c4 = new Chopstick("4");
  5. Chopstick c5 = new Chopstick("5");
  6. new Philosopher("老子", c1, c2).start();
  7. new Philosopher("孔子", c2, c3).start();
  8. new Philosopher("庄子", c3, c4).start();
  9. new Philosopher("孟子", c4, c5).start();
  10. new Philosopher("朱熹", c5, c1).start();

运行结果

  1. 09:45:10.896 [老子] DEBUG com.zhr.thread.eat.Philosopher - eating...
  2. 09:45:10.896 [庄子] DEBUG com.zhr.thread.eat.Philosopher - eating...
  3. 09:45:11.904 [庄子] DEBUG com.zhr.thread.eat.Philosopher - eating...
  4. 09:45:12.912 [孟子] DEBUG com.zhr.thread.eat.Philosopher - eating...
  5. 09:45:13.944 [老子] DEBUG com.zhr.thread.eat.Philosopher - eating...
  6. 09:45:14.944 [朱熹] DEBUG com.zhr.thread.eat.Philosopher - eating...
  7. 09:45:15.945 [荀子] DEBUG com.zhr.thread.eat.Philosopher - eating...
  8. 09:45:16.946 [庄子] DEBUG com.zhr.thread.eat.Philosopher - eating...
  9. 09:45:17.946 [庄子] DEBUG com.zhr.thread.eat.Philosopher - eating...
  10. 09:45:18.946 [孟子] DEBUG com.zhr.thread.eat.Philosopher - eating...

jconsole 分析

名称: 朱熹
状态: com.zhr.thread.eat.Chopstick@78860217上的BLOCKED, 拥有者: 老子
总阻止数: 3, 总等待数: 1

堆栈跟踪: 
com.zhr.thread.eat.Philosopher.run(Philosopher.java:30)
   - 已锁定 com.zhr.thread.eat.Chopstick@383ed11f

========================================================
名称: 老子
状态: com.zhr.thread.eat.Chopstick@1026466d上的BLOCKED, 拥有者: 孟子
总阻止数: 7, 总等待数: 2

堆栈跟踪: 
com.zhr.thread.eat.Philosopher.run(Philosopher.java:30)
   - 已锁定 com.zhr.thread.eat.Chopstick@78860217

========================================================
名称: 孟子
状态: com.zhr.thread.eat.Chopstick@611422a8上的BLOCKED, 拥有者: 庄子
总阻止数: 5, 总等待数: 2

堆栈跟踪: 
com.zhr.thread.eat.Philosopher.run(Philosopher.java:30)
   - 已锁定 com.zhr.thread.eat.Chopstick@1026466d

========================================================
名称: 庄子
状态: com.zhr.thread.eat.Chopstick@1a64076a上的BLOCKED, 拥有者: 荀子
总阻止数: 15, 总等待数: 4

堆栈跟踪: 
com.zhr.thread.eat.Philosopher.run(Philosopher.java:30)
   - 已锁定 com.zhr.thread.eat.Chopstick@611422a8

========================================================
名称: 荀子
状态: com.zhr.thread.eat.Chopstick@383ed11f上的BLOCKED, 拥有者: 朱熹
总阻止数: 4, 总等待数: 1

堆栈跟踪: 
com.zhr.thread.eat.Philosopher.run(Philosopher.java:30)
   - 已锁定 com.zhr.thread.eat.Chopstick@1a64076a

这种线程没有按预期结束,执行不下去的情况,归类为【活跃性】问题,除了死锁以外,还有活锁和饥饿者两种情况

活锁

活锁出现在两个线程互相改变对方的结束条件,最后谁也无法结束,例如

@Slf4j
public class TestLiveLock {
    static volatile int count = 10;
    static final Object lock = new Object();

    public static void main(String[] args) {
        new Thread(() -> {
            // 期望减到 0 退出循环
            while (count > 0) {
                sleep(2);
                count--;
                log.debug("count: {}", count);
            }
        }, "t1").start();
        new Thread(() -> {
            // 期望超过 20 退出循环
            while (count < 20) {
                sleep(2);
                count++;
                log.debug("count: {}", count);
            }
        }, "t2").start();
    }
}

可以通过增加随机睡眠的时间避免活锁的产生

饥饿

很多教程中把饥饿定义为,一个线程由于优先级太低,始终得不到 CPU 调度执行,也不能够结束,饥饿的情况不
易演示,讲读写锁时会涉及饥饿问题
下面我讲一下我遇到的一个线程饥饿的例子,先来看看使用顺序加锁的方式解决之前的死锁问题
image.png

顺序加锁解决方案
image.png

4.13 ReentrantLock

相对于 synchronized 它具备如下特点

  • 可中断
  • 可以设置超时时间
  • 可以设置为公平锁
  • 支持多个条件变量
  • 与 synchronized 一样,都支持可重入

基本语法

// 获取锁
reentrantLock.lock();
try {
    // 临界区
} finally {
    // 释放锁
    reentrantLock.unlock();
}

可重入

可重入是指同一个线程如果首次获得了这把锁,那么因为它是这把锁的拥有者,因此有权利再次获取这把锁。如果是不可重入锁,那么第二次获得锁时,自己也会被锁挡住

@Slf4j
public class Test1 {
    static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        method1();
    }

    public static void method1() {
        lock.lock();
        try {
            log.debug("execute method1");
            method2();
        } finally {
            lock.unlock();
        }
    }

    public static void method2() {
        lock.lock();
        try {
            log.debug("execute method2");
            method3();
        } finally {
            lock.unlock();
        }
    }

    public static void method3() {
        lock.lock();
        try {
            log.debug("execute method3");
        } finally {
            lock.unlock();
        }
    }
}

运行结果

10:41:49.313 [main] DEBUG com.zhr.thread.reentrantlock.Test1 - execute method1
10:41:55.928 [main] DEBUG com.zhr.thread.reentrantlock.Test1 - execute method2
10:42:00.800 [main] DEBUG com.zhr.thread.reentrantlock.Test1 - execute method3

可打断

示例

@Slf4j
public class Test2 {
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Thread t1 = new Thread(() -> {
            try {
                log.info("尝试获取锁");
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                log.debug("等锁的过程中被打断" + e.toString());
                return;
            }

            try {
                log.info("获得了锁");
            } finally {
                lock.unlock();
            }

        }, "t1");

        lock.lock();
        log.info("main获得了锁");

        t1.start();
        try {
            sleep(1);
            t1.interrupt();
            log.info("进行打断");
        } finally {
            lock.unlock();
        }
    }
}

运行结果

10:56:53.149 [main] INFO com.zhr.thread.reentrantlock.Test2 - main获得了锁
10:56:53.158 [t1] INFO com.zhr.thread.reentrantlock.Test2 - 尝试获取锁
10:56:54.157 [main] INFO com.zhr.thread.reentrantlock.Test2 - 进行打断
10:56:54.157 [t1] DEBUG com.zhr.thread.reentrantlock.Test2 - 等锁的过程中被打断java.lang.InterruptedException

注意如果是不可中断模式,那么即使使用了 interrupt 也不会让等待中断

锁超时

立刻失败

@Slf4j
public class Test3 {
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Thread t1 = new Thread(() -> {
            log.info("尝试获取锁");
            if (!lock.tryLock()) {
                log.info("获取锁失败");

                return;
            }

            try {
                log.info("获取到锁");
            } finally {
                lock.unlock();
            }
        }, "t1");

        try {
            log.info("获取锁");
            lock.lock();
            t1.start();
        } finally {
            //lock.unlock();
        }
    }
}

运行结果

11:11:50.326 [main] INFO com.zhr.thread.reentrantlock.Test3 - 获取锁
11:11:50.332 [t1] INFO com.zhr.thread.reentrantlock.Test3 - 尝试获取锁
11:11:50.333 [t1] INFO com.zhr.thread.reentrantlock.Test3 - 获取锁失败

超时失败

@Slf4j
public class Test4 {
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Thread t1 = new Thread(() -> {
            log.info("尝试获取锁");
            try {
                if (!lock.tryLock(3000, TimeUnit.MILLISECONDS)) {
                    log.info("等待后,获取锁失败");
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.info("获取锁失败");
                return;
            }
            try {
                log.info("获取到锁");
            } finally {
                lock.unlock();
            }
        }, "t1");

        try {
            log.info("获取锁");
            lock.lock();
            t1.start();
            sleep(4);
        } finally {
            lock.unlock();
        }
    }
}

运行结果

13:24:55.963 [main] INFO com.zhr.thread.reentrantlock.Test4 - 获取锁
13:24:55.968 [t1] INFO com.zhr.thread.reentrantlock.Test4 - 尝试获取锁
13:24:58.973 [t1] INFO com.zhr.thread.reentrantlock.Test4 - 等待后,获取锁失败

使用 tryLock 解决哲学家就餐问题

class Chopstick extends ReentrantLock {
    String name;

    public Chopstick(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "筷子{" + name + '}';
    }
}
@Slf4j
class Philosopher extends Thread {
    Chopstick left;
    Chopstick right;

    public Philosopher(String name, Chopstick left, Chopstick right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    private void eat() {
        log.debug("eating...");
        Utils.sleep(1);
    }

    @Override
    public void run() {
        while (true) {
            // 获得左手筷子
            if (left.tryLock()) {
                try {
                    // 获得右手筷子
                    if (right.tryLock()) {
                        try {
                            // 吃饭
                            eat();
                        } finally {
                            right.unlock();
                        }
                    }
                    // 放下右手筷子
                } finally {
                    left.unlock();
                }
            }
            // 放下左手筷子
        }
    }
}

公平锁

ReentrantLock 默认是不公平的

@Slf4j
public class TestFair {
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock(false);
        lock.lock();
        for (int i = 0; i < 500; i++) {
            new Thread(() -> {
                lock.lock();
                try {
                    log.info(Thread.currentThread().getName() + " running...");
                } finally {
                    lock.unlock();
                }
            }, "t" + i).start();
        }
        // 1s 之后去争抢锁
        Thread.sleep(1000);
        new Thread(() -> {
            log.info(Thread.currentThread().getName() + " start...");
            lock.lock();
            try {
                log.info(Thread.currentThread().getName() + " running...");
            } finally {
                lock.unlock();
            }
        }, "强行插入").start();
        lock.unlock();
    }
}

强行插入,有机会在中间输出

注意:该实验不一定总能复现

运行结果

13:37:43.992 [t1] INFO com.zhr.thread.reentrantlock.TestFair - t1 running...
13:37:43.992 [强行插入] INFO com.zhr.thread.reentrantlock.TestFair - 强行插入 start...
13:37:43.997 [强行插入] INFO com.zhr.thread.reentrantlock.TestFair - 强行插入 running...
13:37:43.998 [t0] INFO com.zhr.thread.reentrantlock.TestFair - t0 running...
13:37:43.998 [t2] INFO com.zhr.thread.reentrantlock.TestFair - t2 running...

改为公平锁后

ReentrantLock lock = new ReentrantLock(true);

强行插入,总是在最后输出

13:43:21.292 [t455] INFO com.zhr.thread.reentrantlock.TestFair - t455 running...
13:43:21.292 [t454] INFO com.zhr.thread.reentrantlock.TestFair - t454 running...
13:43:21.292 [t453] INFO com.zhr.thread.reentrantlock.TestFair - t453 running...
13:43:21.292 [强行插入] INFO com.zhr.thread.reentrantlock.TestFair - 强行插入 running...

公平锁一般没有必要,会降低并发度,后面分析原理时会讲解

条件变量(Condition)

synchronized 中也有条件变量,就是我们讲原理时那个 waitSet 休息室,当条件不满足时进入 waitSet 等待ReentrantLock 的条件变量比 synchronized 强大之处在于,它是支持多个条件变量的,这就好比

  • synchronized 是那些不满足条件的线程都在一间休息室等消息
  • 而 ReentrantLock 支持多间休息室,有专门等烟的休息室、专门等早餐的休息室、唤醒时也是按休息室来唤醒

使用要点:

  • await 前需要获得锁
  • await 执行后,会释放锁,进入 conditionObject 等待
  • await 的线程被唤醒(或打断、或超时)取重新竞争 lock 锁
  • 竞争 lock 锁成功后,从 await 后继续执行

例子:

@Slf4j
public class Test6 {
    static final ReentrantLock room = new ReentrantLock();
    static boolean hasCigarette = false;
    static boolean hasTakeout = false;
    static Condition cigaretteCondition = room.newCondition();
    static Condition takeoutCondition = room.newCondition();


    public static void main(String[] args) {
        new Thread(() -> {
            room.lock();
            try {
                log.debug("有烟没?[{}]", hasCigarette);
                while (!hasCigarette) {
                    log.debug("没烟,先歇会!");
                    try {
                        cigaretteCondition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("可以开始干活了");
            } finally {
                room.unlock();
            }
        }, "小南").start();
        new Thread(() -> {
            room.lock();
            try {
                log.debug("外卖送到没?[{}]", hasTakeout);
                if (!hasTakeout) {
                    log.debug("没外卖,先歇会!");
                    try {
                        takeoutCondition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("可以开始干活了");
            } finally {
                room.unlock();
            }
        }, "小女").start();
        sleep(1);
        new Thread(() -> {
            room.lock();
            try {
                hasTakeout = true;
                log.debug("外卖到了噢!");
                takeoutCondition.signal();
            } finally {
                room.unlock();
            }
        }, "送外卖的").start();
        sleep(1);
        new Thread(() -> {
            room.lock();
            try {
                hasCigarette = true;
                log.debug("烟到了噢!");
                cigaretteCondition.signal();
            } finally {
                room.unlock();
            }
        }, "买烟的").start();
    }
}

运行结果

14:13:57.652 [小南] DEBUG com.zhr.thread.reentrantlock.Test6 - 有烟没?[false]
14:13:57.658 [小南] DEBUG com.zhr.thread.reentrantlock.Test6 - 没烟,先歇会!
14:13:57.659 [小女] DEBUG com.zhr.thread.reentrantlock.Test6 - 外卖送到没?[false]
14:13:57.659 [小女] DEBUG com.zhr.thread.reentrantlock.Test6 - 没外卖,先歇会!
14:13:58.651 [送外卖的] DEBUG com.zhr.thread.reentrantlock.Test6 - 外卖到了噢!
14:13:58.651 [小女] DEBUG com.zhr.thread.reentrantlock.Test6 - 可以开始干活了
14:13:59.653 [买烟的] DEBUG com.zhr.thread.reentrantlock.Test6 - 烟到了噢!
14:13:59.654 [小南] DEBUG com.zhr.thread.reentrantlock.Test6 - 可以开始干活了

同步模式之顺序控制

1. 固定运行顺序

比如,必须先 1 后 2 打印

1.1 wait notify 版
/**
 * T1 线程输出1  T2 线程输出2
 * 必须先输出1 再输出2
 */
@Slf4j
public class Test1 {
    private static Object lock = new Object();
    private static boolean t1Runed = false;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                log.info("1");
                t1Runed=true;
                lock.notify();
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            synchronized (lock) {
                while (!t1Runed) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.info("2");
            }
        }, "t2");

        t2.start();
        t1.start();
    }
}

运行结果

14:37:40.323 [t1] INFO com.zhr.thread.sequencecontrol.Test1 - 1
14:37:40.327 [t2] INFO com.zhr.thread.sequencecontrol.Test1 - 2

1.2 ReentrantLock 版
/**
 * T1 线程输出1  T2 线程输出2
 * 必须先输出1 再输出2
 */
@Slf4j
public class Test2 {
    private static ReentrantLock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();
    private static boolean t1Runed = false;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            lock.lock();
            try {
                log.info("1");
                t1Runed = true;
                condition.signal();
            } finally {
                lock.unlock();
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            lock.lock();
            try {
                while (!t1Runed) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.info("2");
            } finally {
                lock.unlock();
            }
        }, "t2");

        t1.start();
        t2.start();
    }
}

1.3 Park Unpark 版

可以看到,实现上很麻烦:
首先,需要保证先 wait 再 notify,否则 wait 线程永远得不到唤醒。因此使用了『运行标记』来判断该不该wait
第二,如果有些干扰线程错误地 notify 了 wait 线程,条件不满足时还要重新等待,使用了 while 循环来解决此问题
最后,唤醒对象上的 wait 线程需要使用 notifyAll,因为『同步对象』上的等待线程可能不止一个可以使用 LockSupport 类的 park 和 unpark 来简化上面的题目:

/**
 * T1 线程输出1  T2 线程输出2
 * 必须先输出1 再输出2
 */
@Slf4j
public class Test3 {
    public static void main(String[] args) {
        Thread t2 = new Thread(() -> {
            LockSupport.park();
            log.info("2");
        }, "t2");
        Thread t1 = new Thread(() -> {
            log.info("1");
            LockSupport.unpark(t2);
        }, "t1");

        t1.start();
        t2.start();
    }
}

park 和 unpark 方法比较灵活,他俩谁先调用,谁后调用无所谓。并且是以线程为单位进行『暂停』和『恢复』,
不需要『同步对象』和『运行标记』

2. 交替输出

线程 1 输出 a 5 次,线程 2 输出 b 5 次,线程 3 输出 c 5 次。现在要求输出 abcabcabcabcabc 怎么实现

2.1 wait notify 版
public class Test4 {
    public static void main(String[] args) {
        WaitNotify waitNotify = new WaitNotify(1, 5);
        new Thread(() -> waitNotify.print("a", 1, 2), "t1").start();
        new Thread(() -> waitNotify.print("b", 2, 3), "t2").start();
        new Thread(() -> waitNotify.print("c", 3, 1), "t3").start();
    }
}

class WaitNotify {
    private int currentFlag;
    private final int loopNumber;

    public WaitNotify(int currentFlag, int loopNumber) {
        this.currentFlag = currentFlag;
        this.loopNumber = loopNumber;
    }

    public void print(String str, int waitFlag, int nextFlag) {
        for (int i = 0; i < loopNumber; i++) {
            synchronized (this) {
                while (currentFlag != waitFlag) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(str);
                currentFlag = nextFlag;
                notifyAll();
            }
        }
    }
}

运行结果

abcabcabcabcabc

2.2 Lock 条件变量版
public class Test5 {
    public static void main(String[] args) {
        AwaitSignal waitNotify = new AwaitSignal(5);
        Condition a = waitNotify.newCondition();
        Condition b = waitNotify.newCondition();
        Condition c = waitNotify.newCondition();
        new Thread(() -> waitNotify.print("a", a, b)).start();
        new Thread(() -> waitNotify.print("b", b, c)).start();
        new Thread(() -> waitNotify.print("c", c, a)).start();
        sleep(1);
        waitNotify.lock();
        try {
            a.signal();
        } finally {
            waitNotify.unlock();
        }
    }
}

class AwaitSignal extends ReentrantLock {
    private final int loopNumber;

    public AwaitSignal(int loopNumber) {
        this.loopNumber = loopNumber;
    }

    public void print(String str, Condition current, Condition next) {
        for (int i = 0; i < loopNumber; i++) {
            lock();
            try {
                current.await();
                System.out.print(str);
                next.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                unlock();
            }
        }
    }
}
abcabcabcabcabc

注意 该实现没有考虑 a,b,c 线程都就绪再开始

2.3 Park Unpark 版
public class Test6 {
    private static Thread t1;
    private static Thread t2;
    private static Thread t3;

    public static void main(String[] args) {
        ParkUnPark parkUnPark = new ParkUnPark(5);
        t1 = new Thread(() -> parkUnPark.print("a", t2));
        t2 = new Thread(() -> parkUnPark.print("b", t3));
        t3 = new Thread(() -> parkUnPark.print("c", t1));

        t1.start();
        t2.start();
        t3.start();
        LockSupport.unpark(t1);
    }
}

class ParkUnPark {
    private int loopNumber;

    public ParkUnPark(int loopNumber) {
        this.loopNumber = loopNumber;
    }

    public void print(String str, Thread next) {
        for (int i = 0; i < loopNumber; i++) {
            LockSupport.park();
            System.out.print(str);
            LockSupport.unpark(next);
        }
    }
}

本章小结

本章我们需要重点掌握的是

  • 分析多线程访问共享资源时,哪些代码片段属于临界区
  • 使用 synchronized 互斥解决临界区的线程安全问题
    • 掌握 synchronized 锁对象语法
    • 掌握 synchronzied 加载成员方法和静态方法语法
    • 掌握 wait/notify 同步方法
  • 使用 lock 互斥解决临界区的线程安全问题
    • 掌握 lock 的使用细节:可打断、锁超时、公平锁、条件变量
  • 学会分析变量的线程安全性、掌握常见线程安全类的使用
  • 了解线程活跃性问题:死锁、活锁、饥饿
  • 应用方面
    • 互斥:使用 synchronized 或 Lock 达到共享资源互斥效果
    • 同步:使用 wait/notify 或 Lock 的条件变量来达到线程间通信效果
  • 原理方面
    • monitor、synchronized 、wait/notify 原理
    • synchronized 进阶原理
    • park & unpark 原理
  • 模式方面
    • 同步模式之保护性暂停
    • 异步模式之生产者消费者
    • 同步模式之顺序控制