4.共享模型之管程 本章内容
共享问题
synchronized
线程安全分析
Monitor
wait/notify
线程状态转换
活跃性
Lock
4.1共享带来的问题 Java代码示例 两个线程对初始值为 0 的静态变量一个做自增,一个做自减,各做 5000 次,结果是 0 吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 static int counter = 0 ;public static void main (String[] args) throws InterruptedException { Thread t1 = new Thread (() -> { for (int i = 0 ; i < 5000 ; i++) { counter++; } }, "t1" ); Thread t2 = new Thread (() -> { for (int i = 0 ; i < 5000 ; i++) { counter--; } }, "t2" ); t1.start(); t2.start(); t1.join(); t2.join(); log.debug("{}" ,counter); }
问题分析 以上的结果可能是正数、负数、零。为什么呢?因为 Java 中对静态变量的自增,自减并不是原子操作,要彻底理解,必须从字节码来进行分析 例如对于 i++ 而言(i 为静态变量),实际会产生如下的 JVM 字节码指令:
1 2 3 4 getstatic i iconst_1 iadd putstatic i
而对应 i– 也是类似:
1 2 3 4 getstatic i iconst_1 isub putstatic i
而 Java 的内存模型如下,完成静态变量的自增,自减需要在主存和工作内存中进行数据交换:
如果是单线程以上 8 行代码是顺序执行(不会交错)没有问题:
但多线程下这 8 行代码可能交错运行: 出现负数的情况:
出现正数的情况:
临界区 Critical Section
一个程序运行多个线程本身是没有问题的
问题出在多个线程访问共享资源
多个线程读共享资源 其实也没有问题
在多个线程对共享资源 读写操作时发生指令交错,就会出现问题
一段代码块内如果存在对共享资源的多线程读写操作,称这段代码块为临界区
1 2 3 4 5 6 7 8 9 10 11 static int counter = 0 ;static void increment () { counter++; } static void decrement () { counter--; }
竞态条件 Race Condition 多个线程在临界区内执行,由于代码的执行序列不同 而导致结果无法预测,称之为发生了竞态条件
4.2 synchronized 解决方案 应用之互斥 为了避免临界区的竞态条件发生,有多种手段可以达到目的。
阻塞式的解决方案:synchronized,Lock
非阻塞式的解决方案:原子变量 本次课使用阻塞式的解决方案:synchronized,来解决上述问题,即俗称的【对象锁】,它采用互斥的方式让同一 时刻至多只有一个线程能持有【对象锁】,其它线程再想获取这个【对象锁】时就会阻塞住。这样就能保证拥有锁 的线程可以安全的执行临界区内的代码,不用担心线程上下文切换
注意 虽然 java 中互斥和同步都可以采用 synchronized 关键字来完成,但它们还是有区别的:
互斥是保证临界区的竞态条件发生,同一时刻只能有一个线程执行临界区代码
同步是由于线程执行的先后、顺序不同、需要一个线程等待其它线程运行到某个点
synchronized 语法
1 2 3 4 synchronized (对象) { 临界区 }
解决
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 static int counter = 0 ;static final Object room = new Object ();public static void main (String[] args) throws InterruptedException { Thread t1 = new Thread (() -> { for (int i = 0 ; i < 5000 ; i++) { synchronized (room) { counter++; } } }, "t1" ); Thread t2 = new Thread (() -> { for (int i = 0 ; i < 5000 ; i++) { synchronized (room) { counter--; } } }, "t2" ); t1.start(); t2.start(); t1.join(); t2.join(); log.debug("{}" ,counter); }
图示流程
思考 synchronized 实际是用对象锁保证了临界区内代码的原子性,临界区内的代码对外是不可分割的,不会被线程切 换所打断。 为了加深理解,请思考下面的问题
如果把 synchronized(obj) 放在 for 循环的外面,如何理解?– 原子性
如果 t1 synchronized(obj1) 而 t2 synchronized(obj2) 会怎样运作?– 锁对象
如果 t1 synchronized(obj) 而 t2 没有加会怎么样?如何理解?– 锁对象
面向对象改进 把需要保护的共享变量放入一个类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 class Room { int value = 0 ; public void increment () { synchronized (this ) { value++; } } public void decrement () { synchronized (this ) { value--; } } public int get () { synchronized (this ) { return value; } } } @Slf4j public class Test1 { public static void main (String[] args) throws InterruptedException { Room room = new Room (); Thread t1 = new Thread (() -> { for (int j = 0 ; j < 5000 ; j++) { room.increment(); } }, "t1" ); Thread t2 = new Thread (() -> { for (int j = 0 ; j < 5000 ; j++) { room.decrement(); } }, "t2" ); t1.start(); t2.start(); t1.join(); t2.join(); log.debug("count: {}" , room.get()); } }
4.3 方法上的 synchronized
1 2 3 4 5 6 7 8 9 10 11 12 13 class Test { public synchronized void test () { } } class Test { public void test () { synchronized (this ) { } } }
1 2 3 4 5 6 7 8 9 10 11 12 class Test { public synchronized static void test () { } } 等价于 class Test { public static void test () { synchronized (Test.class) { } } }
不加 synchronized 的方法 不加 synchronzied 的方法就好比不遵守规则的人,不去老实排队(好比翻窗户进去的)
所谓的“线程八锁” 其实就是考察 synchronized 锁住的是哪个对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 @Slf4j(topic = "c.Number") class Number { public synchronized void a () { log.debug("1" ); } public synchronized void b () { log.debug("2" ); } } public static void main (String[] args) { Number n1 = new Number (); new Thread (()->{ n1.a(); }).start(); new Thread (()->{ n1.b(); }).start(); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @Slf4j(topic = "c.Number") class Number { public synchronized void a () { sleep(1 ); log.debug("1" ); } public synchronized void b () { log.debug("2" ); } } public static void main (String[] args) { Number n1 = new Number (); new Thread (()->{ n1.a(); }).start(); new Thread (()->{ n1.b(); }).start(); }
情况3:
3 1s 12
或 23 1s 1
或 32 1s 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 @Slf4j(topic = "c.Number") class Number { public synchronized void a () { sleep(1 ); log.debug("1" ); } public synchronized void b () { log.debug("2" ); } public void c () { log.debug("3" ); } } public static void main (String[] args) { Number n1 = new Number (); new Thread (()->{ n1.a(); }).start(); new Thread (()->{ n1.b(); }).start(); new Thread (()->{ n1.c(); }).start(); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @Slf4j(topic = "c.Number") class Number { public synchronized void a () { sleep(1 ); log.debug("1" ); } public synchronized void b () { log.debug("2" ); } } public static void main (String[] args) { Number n1 = new Number (); Number n2 = new Number (); new Thread (()->{ n1.a(); }).start(); new Thread (()->{ n2.b(); }).start(); }
情况5:
a是静态,锁的类对象
b是方法,所得对象
两个不互斥
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @Slf4j(topic = "c.Number") class Number { public static synchronized void a () { sleep(1 ); log.debug("1" ); } public synchronized void b () { log.debug("2" ); } } public static void main (String[] args) { Number n1 = new Number (); new Thread (()->{ n1.a(); }).start(); new Thread (()->{ n1.b(); }).start(); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @Slf4j(topic = "c.Number") class Number { public static synchronized void a () { sleep(1 ); log.debug("1" ); } public static synchronized void b () { log.debug("2" ); } } public static void main (String[] args) { Number n1 = new Number (); new Thread (()->{ n1.a(); }).start(); new Thread (()->{ n1.b(); }).start(); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @Slf4j(topic = "c.Number") class Number { public static synchronized void a () { sleep(1 ); log.debug("1" ); } public synchronized void b () { log.debug("2" ); } } public static void main (String[] args) { Number n1 = new Number (); Number n2 = new Number (); new Thread (()->{ n1.a(); }).start(); new Thread (()->{ n2.b(); }).start(); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @Slf4j(topic = "c.Number") class Number { public static synchronized void a () { sleep(1 ); log.debug("1" ); } public static synchronized void b () { log.debug("2" ); } } public static void main (String[] args) { Number n1 = new Number (); Number n2 = new Number (); new Thread (()->{ n1.a(); }).start(); new Thread (()->{ n2.b(); }).start(); }
4.4 变量的线程安全分析 成员变量和静态变量是否线程安全?
如果它们没有共享,则线程安全
如果它们被共享了,根据它们的状态是否能够改变,又分两种情况
如果只有读操作,则线程安全
如果有读写操作,则这段代码是临界区,需要考虑线程安全
局部变量是否线程安全?
局部变量是线程安全的
但局部变量引用的对象则未必 Object a = new Object()
如果该对象没有逃离方法的作用访问,它是线程安全的
如果该对象逃离方法的作用范围,需要考虑线程安全
局部变量线程安全分析 普通局部变量(安全) 1 2 3 4 public static void test1 () { int i = 10 ; i++; }
每个线程调用 test1() 方法时局部变量 i,会在每个线程的栈帧内存中被创建多份,因此不存在共享
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public static void test1 () ; descriptor: ()V flags: ACC_PUBLIC, ACC_STATIC Code: stack=1 , locals=1 , args_size=0 0 : bipush 10 2 : istore_0 3 : iinc 0 , 1 6 : return LineNumberTable: line 10 : 0 line 11 : 3 line 12 : 6 LocalVariableTable: Start Length Slot Name Signature 3 4 0 i I
如图:
每个线程有独立的栈帧 局部变量的引用稍有不同
成员变量(不安全) 先看一个成员变量的例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class ThreadUnsafe { ArrayList<String> list = new ArrayList <>(); public void method1 (int loopNumber) { for (int i = 0 ; i < loopNumber; i++) { method2(); method3(); } } private void method2 () { list.add("1" ); } private void method3 () { list.remove(0 ); } }
执行
两个线程对 对象的成员变量list做增加减少元素
引发线程安全问题,出现下标越界问题
1 2 3 4 5 6 7 8 9 10 11 12 static final int THREAD_NUMBER = 2 ;static final int LOOP_NUMBER = 200 ;public static void main (String[] args) { ThreadUnsafe test = new ThreadUnsafe (); for (int i = 0 ; i < THREAD_NUMBER; i++) { new Thread (() -> { test.method1(LOOP_NUMBER); }, "Thread" + i).start(); } }
其中一种情况是,如果线程2 还未 add,线程1 remove 就会报错:
1 2 3 4 5 6 7 Exception in thread "Thread1" java.lang.IndexOutOfBoundsException: Index: 0 , Size: 0 at java.util.ArrayList.rangeCheck(ArrayList.java:657 ) at java.util.ArrayList.remove(ArrayList.java:496 ) at cn.itcast.n6.ThreadUnsafe.method3(TestThreadSafe.java:35 ) at cn.itcast.n6.ThreadUnsafe.method1(TestThreadSafe.java:26 ) at cn.itcast.n6.TestThreadSafe.lambda$main$0 (TestThreadSafe.java:14 ) at java.lang.Thread.run(Thread.java:748 )
分析:
无论哪个线程中的 method2 引用的都是同一个对象中的 list 成员变量
method3 与 method2 分析相同
局部对象变量(安全) 将 list 修改为局部变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class ThreadSafe { public final void method1 (int loopNumber) { ArrayList<String> list = new ArrayList <>(); for (int i = 0 ; i < loopNumber; i++) { method2(list); method3(list); } } private void method2 (ArrayList<String> list) { list.add("1" ); } private void method3 (ArrayList<String> list) { list.remove(0 ); } }
那么就不会有上述问题了
分析:
本质就是线程1和线程2分别在堆中创建了两个不同的list
list 是局部变量,每个线程调用时会创建其不同实例,没有共享
而 method2 的参数是从 method1 中传递过来的,与 method1 中引用同一个对象
method3 的参数分析与 method2 相同
局部对象变量+子类(不安全) 方法访问修饰符带来的思考,如果把 method2 和 method3 的方法修改为 public 会不会代理线程安全问题?
情况1:有其它线程调用 method2 和 method3
情况2:在 情况1 的基础上,为 ThreadSafe 类添加子类,子类覆盖 method2 或 method3 方法,
ThreadSafeSubClass 重写父类方法,开一个线程,访问的是同一个list
若是 public void method3则子类可以重写方法,开线程,则不安全
因此要用 public void method3, 保证子类不能重写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 public class TestThreadSafe { static final int THREAD_NUMBER = 2 ; static final int LOOP_NUMBER = 200 ; public static void main (String[] args) { ThreadSafeSubClass test = new ThreadSafeSubClass (); for (int i = 0 ; i < THREAD_NUMBER; i++) { new Thread (() -> { test.method1(LOOP_NUMBER); }, "Thread" + (i + 1 )).start(); } } } class ThreadSafe { public final void method1 (int loopNumber) { ArrayList<String> list = new ArrayList <>(); for (int i = 0 ; i < loopNumber; i++) { method2(list); method3(list); } } private void method2 (ArrayList<String> list) { list.add("1" ); } public void method3 (ArrayList<String> list) { list.remove(0 ); } } class ThreadSafeSubClass extends ThreadSafe { @Override public void method3 (ArrayList<String> list) { new Thread (() -> { list.remove(0 ); }).start(); } }
从这个例子可以看出 private 或 final 提供【安全】的意义所在,请体会开闭原则中的【闭】
常见线程安全类
String
Integer
StringBuffer
Random
Vector 线程安全的List
Hashtable 线程安全的Map
java.util.concurrent 包下的类
这里说它们是线程安全的是指:多个线程调用它们同一个实例的某个方法时,是线程安全的 。
也可以理解为:
1 2 3 4 5 6 7 8 9 Hashtable table = new Hashtable ();new Thread (()->{ table.put("key" , "value1" ); }).start(); new Thread (()->{ table.put("key" , "value2" ); }).start();
它们的每个方法是原子的
但注意它们多个方法的组合不是原子的,见后面分析
线程安全类方法的组合 分析下面代码是否线程安全?
get方法线程安全
put方法线程安全
两个组合后线程不安全
线程2 put覆盖了线程1的值
1 2 3 4 5 Hashtable table = new Hashtable ();if ( table.get("key" ) == null ) { table.put("key" , value); }
不可变类线程安全性
String、Integer 等都是不可变类,因为其内部的状态不可以改变,因此它们的方法都是线程安全的
有同学或许有疑问,String 有 replace,substring 等方法【可以】改变值啊,那么这些方法又是如何保证线程安 全的呢?
没有改变对象属性,做了 copy
1 2 3 4 5 6 7 8 9 public class Immutable { private int value = 0 ; public Immutable (int value) { this .value = value; } public int getValue () { return this .value; } }
如果想增加一个增加的方法呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 public class Immutable { private int value = 0 ; public Immutable (int value) { this .value = value; } public int getValue () { return this .value; } public Immutable add (int v) { return new Immutable (this .value + v); } }
实例分析 例1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public class MyServlet extends HttpServlet { Map<String,Object> map = new HashMap <>(); String S1 = "..." ; final String S2 = "..." ; Date D1 = new Date (); final Date D2 = new Date (); public void doGet (HttpServletRequest request, HttpServletResponse response) { } }
例2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class MyServlet extends HttpServlet { private UserService userService = new UserServiceImpl (); public void doGet (HttpServletRequest request, HttpServletResponse response) { userService.update(...); } } public class UserServiceImpl implements UserService { private int count = 0 ; public void update () { count++; } }
例3:
求运行时间差值
线程不安全
对象的成员变量start修改
结局:环绕通知 把时间做方法的局部变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 @Aspect @Component public class MyAspect { private long start = 0L ; @Before("execution(* *(..))") public void before () { start = System.nanoTime(); } @After("execution(* *(..))") public void after () { long end = System.nanoTime(); System.out.println("cost time:" + (end-start)); } }
例4: 三层结构调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 public class MyServlet extends HttpServlet { private UserService userService = new UserServiceImpl (); public void doGet (HttpServletRequest request, HttpServletResponse response) { userService.update(...); } } public class UserServiceImpl implements UserService { private UserDao userDao = new UserDaoImpl (); public void update () { userDao.update(); } } public class UserDaoImpl implements UserDao { public void update () { String sql = "update user set password = ? where username = ?" ; try (Connection conn = DriverManager.getConnection("" ,"" ,"" )){ } catch (Exception e) { } } }
例5:
private Connection conn = null; 不安全,成员变量 conn.close();改变状态
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 public class MyServlet extends HttpServlet { private UserService userService = new UserServiceImpl (); public void doGet (HttpServletRequest request, HttpServletResponse response) { userService.update(...); } } public class UserServiceImpl implements UserService { private UserDao userDao = new UserDaoImpl (); public void update () { userDao.update(); } } public class UserDaoImpl implements UserDao { private Connection conn = null ; public void update () throws SQLException { String sql = "update user set password = ? where username = ?" ; conn = DriverManager.getConnection("" ,"" ,"" ); conn.close(); } }
例6:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 public class MyServlet extends HttpServlet { private UserService userService = new UserServiceImpl (); public void doGet (HttpServletRequest request, HttpServletResponse response) { userService.update(...); } } public class UserServiceImpl implements UserService { public void update () { UserDao userDao = new UserDaoImpl (); userDao.update(); } } public class UserDaoImpl implements UserDao { private Connection = null ; public void update () throws SQLException { String sql = "update user set password = ? where username = ?" ; conn = DriverManager.getConnection("" ,"" ,"" ); conn.close(); } }
例7:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public abstract class Test { public void bar () { SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss" ); foo(sdf); } public abstract foo (SimpleDateFormat sdf) ; public static void main (String[] args) { new Test ().bar(); } }
其中 foo 的行为是不确定的,可能导致不安全的发生,被称之为外星方法
1 2 3 4 5 6 7 8 9 10 11 12 public void foo (SimpleDateFormat sdf) { String dateStr = "1999-10-11 00:00:00" ; for (int i = 0 ; i < 20 ; i++) { new Thread (() -> { try { sdf.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } }).start(); } }
请比较 JDK 中 String 类的实现
例8:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 private static Integer i = 0 ;public static void main (String[] args) throws InterruptedException { List<Thread> list = new ArrayList <>(); for (int j = 0 ; j < 2 ; j++) { Thread thread = new Thread (() -> { for (int k = 0 ; k < 5000 ; k++) { synchronized (i) { i++; } } }, "" + j); list.add(thread); } list.stream().forEach(t -> t.start()); list.stream().forEach(t -> { try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); log.debug("{}" , i); }
4.5 习题 卖票练习 测试下面代码是否存在线程安全问题,并尝试改正
将sell方法声明为synchronized即可
注意只将对count进行修改的一行代码用synchronized括起来也不行。对count大小的判断也必须是为原子操作的一部分,否则也会导致count值异常。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 @Slf4j(topic = "c.ExerciseSell") public class ExerciseSell { public static void main (String[] args) throws InterruptedException { TicketWindow window = new TicketWindow (1000 ); List<Thread> threadList = new ArrayList <>(); List<Integer> amountList = new Vector <>(); for (int i = 0 ; i < 2000 ; i++) { Thread thread = new Thread (() -> { int amount = window.sell(random(5 )); amountList.add(amount); }); threadList.add(thread); thread.start(); } for (Thread thread : threadList) { thread.join(); } log.debug("余票:{}" , window.getCount()); log.debug("卖出的票数:{}" , amountList.stream().mapToInt(i -> i).sum()); } static Random random = new Random (); return random.nextInt(amount) + 1 ; } } class TicketWindow { private int count; public TicketWindow (int count) { this .count = count; } public int getCount () { return count; } public synchronized int sell (int amount) { if (this .count >= amount) { this .count -= amount; return amount; } else { return 0 ; } } }
另外,用下面的代码行不行,为什么?
不行,因为sellCount会被多个线程共享,必须使用线程安全的实现类。
1 List<Integer> sellCount = new ArrayList <>();
测试脚本
1 for /L %n in (1,1,10) do java -cp ".;C:\Users\manyh\.m2\repository\ch\qos\logback\logbackclassic\1.2.3\logback-classic-1.2.3.jar;C:\Users\manyh\.m2\repository\ch\qos\logback\logbackcore\1.2.3\logback-core-1.2.3.jar;C:\Users\manyh\.m2\repository\org\slf4j\slf4japi\1.7.25\slf4j-api-1.7.25.jar" cn.itcast.n4.exercise.ExerciseSell
说明:
两段没有前后因果关系的临界区代码,只需要保证各自的原子性即可,不需要括起来。 解决方法:sell方法加上 synchronized
1 2 3 4 5 6 7 8 9 public synchronized int sell (int amount) { if (this .count >= amount) { this .count -= amount; return amount; } else { return 0 ; } }
转账练习 测试下面代码是否存在线程安全问题,并尝试改正
将transfer方法的方法体用同步代码块包裹,将当Account.class设为锁对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 public class ExerciseTransfer { public static void main (String[] args) throws InterruptedException { Account a = new Account (1000 ); Account b = new Account (1000 ); Thread t1 = new Thread (() -> { for (int i = 0 ; i < 1000 ; i++) { a.transfer(b, randomAmount()); } }, "t1" ); Thread t2 = new Thread (() -> { for (int i = 0 ; i < 1000 ; i++) { b.transfer(a, randomAmount()); } }, "t2" ); t1.start(); t2.start(); t1.join(); t2.join(); log.debug("total:{}" ,(a.getMoney() + b.getMoney())); } static Random random = new Random (); public static int randomAmount () { return random.nextInt(100 ) +1 ; } } class Account { private int money; public Account (int money) { this .money = money; } public int getMoney () { return money; } public void setMoney (int money) { this .money = money; } public void transfer (Account target, int amount) { if (this .money > amount) { this .setMoney(this .getMoney() - amount); target.setMoney(target.getMoney() + amount); } } }
结果:
初始金额各自1000,总金额2000
最后总和没有2000
1 15:12:19.529 c.ExerciseTransfer [main] - total:47
这样改正行不行,为什么?
1 2 3 4 5 6 public synchronized void transfer (Account target, int amount) { if (this .money > amount) { this .setMoney(this .getMoney() - amount); target.setMoney(target.getMoney() + amount); } }
正确方法:
1 2 3 4 5 6 7 8 public void transfer (Account target, int amount) { synchronized (Account.class) { if (this .money >= amount) { this .setMoney(this .getMoney() - amount); target.setMoney(target.getMoney() + amount); } } }
4.6 Monitor 概念 Java 对象头 以 32 位虚拟机为例 普通对象
1 2 3 4 5 |-------------------------------------------------------------- | | Object Header (64 bits) | |------------------------------------ |-------------------------| | Mark Word (32 bits) | Klass Word (32 bits) ||------------------------------------ |-------------------------|
数组对象
1 2 3 4 5 |--------------------------------------------------------------------------------- | | Object Header (96 bits) | |-------------------------------- |-----------------------|------------------------ | | Mark Word(32bits) | Klass Word (32bits) | array length(32bits) | |-------------------------------- |-----------------------|------------------------ |
其中 Mark Word 结构为
1 2 3 4 5 6 7 8 9 10 11 12 13 |------------------------------------------------------- |--------------------| | 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 | |------------------------------------------------------- |--------------------|
64 位虚拟机 Mark Word
1 2 3 4 5 6 7 8 9 10 11 12 13 |-------------------------------------------------------------------- |--------------------| | 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 结构如下
刚开始 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 2 3 4 5 6 7 static final Object lock = new Object ();static int counter = 0 ;public static void main (String[] args) { synchronized (lock) { counter++; } }
对应的字节码为:
关注 Exception table 有量出,保证出现异常仍能释放锁
19~23行处理异常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 public static void main (java.lang.String[]) ;descriptor: ([Ljava/lang/String;)V flags: ACC_PUBLIC, ACC_STATIC Code: stack=2 , locals=3 , args_size=1 0 : getstatic #2 3 : dup 4 : astore_1 5 : monitorenter 6 : getstatic #3 9 : iconst_1 10 : iadd 11 : putstatic #3 14 : aload_1 15 : monitorexit 16 : goto 24 19 : astore_2 20 : aload_1 21 : monitorexit 22 : aload_2 23 : athrow 24 : return Exception table: from to target type 6 16 19 any 19 22 19 any LineNumberTable: line 8 : 0 line 9 : 6 line 10 : 14 line 11 : 24 LocalVariableTable: Start Length Slot Name Signature 0 25 0 args [Ljava/lang/String; StackMapTable: number_of_entries = 2 frame_type = 255 offset_delta = 19 locals = [ class "[Ljava/lang/String;" , class java /lang/Object ] stack = [ class java /lang/Throwable ] frame_type = 250 offset_delta = 4
注意
方法级别的 synchronized 不会在字节码指令中有所体现
* 原理之 synchronized 进阶 1. 轻量级锁
轻量级锁的使用场景:==如果一个对象虽然有多线程要加锁,但加锁的时间是错开的(也就是没有竞争),那么可以使用轻量级锁来优化。 ==
本质是栈中的锁记录
轻量级锁对使用者是透明的,即语法仍然是 synchronized 假设有两个方法同步块,利用同一个对象加锁
1 2 3 4 5 6 7 8 9 10 11 12 static final Object obj = new Object ();public static void method1 () { synchronized ( obj ) { method2(); } } public static void method2 () { synchronized ( obj ) { } }
创建锁记录(Lock Record)对象,每个线程都的栈帧都会包含一个锁记录的结构,内部可以存储锁定对象的 Mark Word和对象地址
让锁记录中 Object reference 指向锁对象,并尝试用 cas 替换 Object 的 Mark Word,将 Mark Word 的值存 入锁记录
00是轻量级锁
如果 cas 替换成功,对象头中存储了 锁记录地址和状态 00 ,表示由该线程给对象加锁,这时图示如下
如果 cas 失败,有两种情况
如果是其它线程已经持有了该 Object 的轻量级锁,这时表明有竞争,进入锁膨胀过程
如果是自己执行了 synchronized 锁重入,那么再添加一条 Lock Record 作为重入的计数
锁重入情况:方法嵌套调用,锁的同一个对象
当退出 synchronized 代码块(解锁时)如果有取值为 null 的锁记录,表示有重入,这时重置锁记录,表示重 入计数减一
当退出 synchronized 代码块(解锁时)锁记录的值不为 null,这时使用cas将Mark Word的值恢复给对象头
成功,则解锁成功
失败,说明轻量级锁进行了锁膨胀或已经升级为重量级锁,进入重量级锁解锁流程
2. 锁膨胀
如果在尝试加轻量级锁的过程中,CAS 操作无法成功,这时一种情况就是有其它线程为此对象加上了轻量级锁(有竞争),这时需要进行锁膨胀,将轻量级锁变为重量级锁。
本质是在堆中创建了Monitor管程
1 2 3 4 5 6 static Object obj = new Object ();public static void method1 () { synchronized ( obj ) { } }
当 Thread-1 进行轻量级加锁时,Thread-0 已经对该对象加了轻量级锁
这时 Thread-1 加轻量级锁失败,进入锁膨胀流程
即为 Object 对象申请 Monitor 锁,让 Object 指向重量级锁地址
然后自己进入 Monitor 的 EntryList BLOCKED
当 Thread-0 退出同步块解锁时,使用 cas 将 Mark Word 的值恢复给对象头,失败。
这时解锁与之前轻量级不同
这时会进入重量级解锁 流程,即按照 Monitor 地址找到 Monitor 对象,设置 Owner 为 null,唤醒 EntryList 中 BLOCKED 线程
3. 自旋优化
重量级锁竞争的时候,还可以使用自旋来进行优化,如果当前线程自旋成功(即这时候持锁线程已经退出了同步块,释放了锁),这时当前线程就可以避免阻塞。
说白了就是不直接进入 EntryList,而是自己反复尝试。
本质是一种机制
自旋重试成功的情况
线程1 ( core 1上)
对象Mark
线程2 ( core 2上)
-
10(重量锁)
-
访问同步块,获取monitor
10(重量锁)重量锁指针
-
成功(加锁)
10(重量锁)重量锁指针
-
执行同步块
10(重量锁)重量锁指针
-
执行同步块
10(重量锁)重量锁指针
访问同步块,获取 monitor
执行同步块
10(重量锁)重量锁指针
自旋重试
执行完毕
10(重量锁)重量锁指针
自旋重试
成功(解锁)
01(无锁)
自旋重试
-
10(重量锁)重量锁指针
成功(加锁)
-
10(重量锁)重量锁指针
执行同步块
-
…
…
自旋重试失败的情况
线程1 ( core 1上)
对象Mark
线程2( core 2上)
-
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 static final Object obj = new Object ();public static void m1 () { synchronized ( obj ) { m2(); } } public static void m2 () { synchronized ( obj ) { m3(); } } public static void m3 () { synchronized ( obj ) { } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 graph LR subgraph 偏向锁 t5("m1内调用synchronized(obj)") t6("m2内调用synchronized(obj)") t7("m2内调用synchronized(obj)") t8(对象) t5 -.用ThreadID替换MarkWord.-> t8 t6 -.检查ThreadID是否是自己.-> t8 t7 -.检查ThreadID是否是自己.-> t8 end subgraph 轻量级锁 t1("m1内调用synchronized(obj)") t2("m2内调用synchronized(obj)") t3("m2内调用synchronized(obj)") t1 -.生成锁记录.-> t1 t2 -.生成锁记录.-> t2 t3 -.生成锁记录.-> t3 t4(对象) t1 -.用锁记录替换markword.-> t4 t2 -.用锁记录替换markword.-> t4 t3 -.用锁记录替换markword.-> t4 end
偏向状态 回忆一下对象头格式
三种锁
normal 正常状态
Biased(偏向):54位记录线程id
Lightweight
Heavyweight
1 2 3 4 5 6 7 8 9 10 11 12 13 |-------------------------------------------------------------------- |--------------------| | 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) 测试偏向锁
利用 jol 第三方工具来查看对象头信息(注意这里我扩展了 jol 让它输出更为简洁)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public static void main (String[] args) throws IOException { Dog d = new Dog (); ClassLayout classLayout = ClassLayout.parseInstance(d); new Thread (() -> { log.debug("synchronized 前" ); System.out.println(classLayout.toPrintableSimple(true )); synchronized (d) { log.debug("synchronized 中" ); System.out.println(classLayout.toPrintableSimple(true )); } log.debug("synchronized 后" ); System.out.println(classLayout.toPrintableSimple(true )); }, "t1" ).start(); }
1 2 3 4 5 6 11:08:58.117 c.TestBiased [t1] - synchronized 前 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000101 11:08:58.121 c.TestBiased [t1] - synchronized 中 00000000 00000000 00000000 00000000 00011111 11101011 11010000 00000101 11:08:58.121 c.TestBiased [t1] - synchronized 后 00000000 00000000 00000000 00000000 00011111 11101011 11010000 00000101
注意
处于偏向锁的对象解锁后,线程 id 仍存储于对象头中
3)测试禁用 在上面测试代码运行时在添加 VM 参数 -XX:-UseBiasedLocking 禁用偏向锁 输出
1 2 3 4 5 6 11:13:10.018 c.TestBiased [t1] - synchronized 前 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 11:13:10.021 c.TestBiased [t1] - synchronized 中 00000000 00000000 00000000 00000000 00100000 00010100 11110011 10001000 11:13:10.021 c.TestBiased [t1] - synchronized 后 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
4)测试 hashCode
正常状态对象一开始是没有 hashCode 的,第一次调用 d.hashcode() 才生成
开始对象是偏向锁的101,调用 d.hashcode() 生成31位hashcode,
由于没地方存储,不得不变为normal状态,此时模为为 001
撤销 - 调用对象 hashCode 调用了对象的 hashCode,但偏向锁的对象 MarkWord 中存储的是线程 id,如果调用 hashCode 会导致偏向锁被 撤销
轻量级锁会在锁记录中记录 hashCode
重量级锁会在 Monitor 中记录 hashCode 在调用 hashCode 后使用偏向锁,记得去掉-XX:-UseBiasedLocking 输出
1 2 3 4 5 6 7 11:22:10.386 c.TestBiased [main] - 调用 hashCode:1778535015 11:22:10.391 c.TestBiased [t1] - synchronized 前 00000000 00000000 00000000 01101010 00000010 01001010 01100111 00000001 11:22:10.393 c.TestBiased [t1] - synchronized 中 00000000 00000000 00000000 00000000 00100000 11000011 11110011 01101000 11:22:10.393 c.TestBiased [t1] - synchronized 后 00000000 00000000 00000000 01101010 00000010 01001010 01100111 00000001
撤销 - 其它线程使用对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 private static void test2 () throws InterruptedException { Dog d = new Dog (); Thread t1 = new Thread (() -> { synchronized (d) { log.debug(ClassLayout.parseInstance(d).toPrintableSimple(true )); } synchronized (TestBiased.class) { TestBiased.class.notify(); } }, "t1" ); t1.start(); Thread t2 = new Thread (() -> { synchronized (TestBiased.class) { try { TestBiased.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } log.debug(ClassLayout.parseInstance(d).toPrintableSimple(true )); synchronized (d) { log.debug(ClassLayout.parseInstance(d).toPrintableSimple(true )); } log.debug(ClassLayout.parseInstance(d).toPrintableSimple(true )); }, "t2" ); t2.start(); }
输出
1 2 3 4 [t1] - 00000000 00000000 00000000 00000000 00011111 01000001 00010000 00000101 偏向 [t2] - 00000000 00000000 00000000 00000000 00011111 01000001 00010000 00000101 偏向 [t2] - 00000000 00000000 00000000 00000000 00011111 10110101 11110000 01000000 轻量级 [t2] - 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 normal 不可偏向
撤销 - 调用 wait/notify 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 public static void main (String[] args) throws InterruptedException { Dog d = new Dog (); Thread t1 = new Thread (() -> { log.debug(ClassLayout.parseInstance(d).toPrintableSimple(true )); synchronized (d) { log.debug(ClassLayout.parseInstance(d).toPrintableSimple(true )); try { d.wait(); } catch (InterruptedException e) { e.printStackTrace(); } log.debug(ClassLayout.parseInstance(d).toPrintableSimple(true )); } }, "t1" ); t1.start(); new Thread (() -> { try { Thread.sleep(6000 ); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (d) { log.debug("notify" ); d.notify(); } }, "t2" ).start(); }
输出
1 2 3 4 [t1] - 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000101 [t1] - 00000000 00000000 00000000 00000000 00011111 10110011 11111000 00000101 [t2] - notify [t1] - 00000000 00000000 00000000 00000000 00011100 11010100 00001101 11001010
批量重偏向 如果对象虽然被多个线程访问,但没有竞争,这时偏向了线程 T1 的对象仍有机会重新偏向 T2,重偏向会重置对象 的 Thread ID 当撤销偏向锁阈值超过 20 次后,jvm 会这样觉得,我是不是偏向错了呢,于是会在给这些对象加锁时重新偏向至 加锁线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 private static void test3 () throws InterruptedException { Vector<Dog> list = new Vector <>(); Thread t1 = new Thread (() -> { for (int i = 0 ; i < 30 ; i++) { Dog d = new Dog (); list.add(d); synchronized (d) { log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true )); } } synchronized (list) { list.notify(); } }, "t1" ); t1.start(); Thread t2 = new Thread (() -> { synchronized (list) { try { list.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } log.debug("===============> " ); for (int i = 0 ; i < 30 ; i++) { Dog d = list.get(i); log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true )); synchronized (d) { log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true )); } log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true )); } }, "t2" ); t2.start(); }
输出
20次后线程id变为t2
[t2] - 20 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 [t1] - 0 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 1 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 2 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 3 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 4 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 5 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 6 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 7 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 8 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 9 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 10 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 11 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 12 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 13 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 14 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 15 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 16 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 17 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 18 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 19 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 20 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 21 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 22 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 23 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 24 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 25 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 26 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 27 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 28 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t1] - 29 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - ===============> [t2] - 0 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 0 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 0 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 1 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 1 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 1 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 2 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 2 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 2 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 3 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 3 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 3 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 4 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 4 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 4 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 5 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 5 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 5 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 6 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 6 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 6 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 7 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 7 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 7 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 8 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 8 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 8 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 9 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 9 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 9 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 10 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 10 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 10 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 11 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 11 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 11 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 12 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 12 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 12 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 13 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 13 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 13 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 14 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 14 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 14 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 15 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 15 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 15 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 16 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 16 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 16 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 17 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 17 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 17 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 18 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 18 00000000 00000000 00000000 00000000 00100000 01011000 11110111 00000000 [t2] - 18 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 [t2] - 19 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 19 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 19 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 20 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 20 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 20 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 21 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 21 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 21 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 22 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 22 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 22 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 23 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 23 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 23 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 24 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 24 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 24 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 25 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 25 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 25 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 26 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 26 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 26 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 27 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 27 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 27 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 28 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 28 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 28 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 29 00000000 00000000 00000000 00000000 00011111 11110011 11100000 00000101 [t2] - 29 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101 [t2] - 29 00000000 00000000 00000000 00000000 00011111 11110011 11110001 00000101
批量撤销 当撤销偏向锁阈值超过 40 次后,jvm 会这样觉得,自己确实偏向错了,根本就不该偏向。于是整个类的所有对象 都会变为不可偏向的,新建的对象也是不可偏向的 001 normal
最后执行 log.debug(ClassLayout.parseInstance(new Dog()).toPrintableSimple(true)); // 不可偏向001
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 static Thread t1,t2,t3;private static void test4 () throws InterruptedException { Vector<Dog> list = new Vector <>(); int loopNumber = 39 ; t1 = new Thread (() -> { for (int i = 0 ; i < loopNumber; i++) { Dog d = new Dog (); list.add(d); synchronized (d) { log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true )); } } LockSupport.unpark(t2); }, "t1" ); t1.start(); t2 = new Thread (() -> { LockSupport.park(); log.debug("===============> " ); for (int i = 0 ; i < loopNumber; i++) { Dog d = list.get(i); log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true )); synchronized (d) { log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true )); } log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true )); } LockSupport.unpark(t3); }, "t2" ); t2.start(); t3 = new Thread (() -> { LockSupport.park(); log.debug("===============> " ); for (int i = 0 ; i < loopNumber; i++) { Dog d = list.get(i); log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true )); synchronized (d) { log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true )); } log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true )); } }, "t3" ); t3.start(); t3.join(); log.debug(ClassLayout.parseInstance(new Dog ()).toPrintableSimple(true )); }
参考资料
https://github.com/farmerjohngit/myblog/issues/12
https://www.cnblogs.com/LemonFive/p/11246086.html
https://www.cnblogs.com/LemonFive/p/11248248.html
[偏向锁论文](Eliminating Synchronization-Related Atomic Operations with Biased Locking and Bulk Rebiasing (oracle.com) )
锁消除 锁消除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 @Fork(1) @BenchmarkMode(Mode.AverageTime) @Warmup(iterations=3) @Measurement(iterations=5) @OutputTimeUnit(TimeUnit.NANOSECONDS) public class MyBenchmark { static int x = 0 ; @Benchmark public void a () throws Exception { x++; } @Benchmark public void b () throws Exception { Object o = new Object (); synchronized (o) { x++; } } }
java -jar benchmarks.jar
1 2 3 Benchmark Mode Samples Score Score error Units c.i.MyBenchmark.a avgt 5 1.542 0.056 ns/op c.i.MyBenchmark.b avgt 5 1.518 0.091 ns/op
1 2 3 Benchmark Mode Samples Score Score error Units c.i.MyBenchmark.a avgt 5 1.507 0.108 ns/op c.i.MyBenchmark.b avgt 5 16.976 1.572 ns/op
锁粗化 对相同对象多次加锁,导致线程发生多次重入,可以使用锁粗化方式来优化,这不同于之前讲的细分锁的粒度。
4.7 wait notify 小故事 - 为什么需要 wait
* 原理之 wait / notify
Owner 线程发现条件不满足,调用 wait 方法,即可进入 WaitSet 变为 WAITING 状态
BLOCKED 和 WAITING 的线程都处于阻塞状态,不占用 CPU 时间片
WAITING 是获得了锁,但是放弃的
BLOCKED是没有活儿锁,需要先竞争锁
BLOCKED 线程会在 Owner 线程释放锁时唤醒
WAITING 线程会在 Owner 线程调用 notify 或 notifyAll 时唤醒,但唤醒后并不意味者立刻获得锁,仍需进入 EntryList 重新竞争
API 介绍
obj.wait() 让进入 object 监视器的线程到 waitSet 等待
obj.notify() 在 object 上正在 waitSet 等待的线程中挑一个唤醒
obj.notifyAll() 让 object 上正在 waitSet 等待的线程全部唤醒 它们都是线程之间进行协作的手段,都属于 Object 对象的方法。必须获得此对象的锁(即Owner),才能调用这几个方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 final static Object obj = new Object ();public static void main (String[] args) { new Thread (() -> { synchronized (obj) { log.debug("执行...." ); try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } log.debug("其它代码...." ); } }).start(); new Thread (() -> { synchronized (obj) { log.debug("执行...." ); try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } log.debug("其它代码...." ); } }).start(); sleep(2 ); log.debug("唤醒 obj 上其它线程" ); synchronized (obj) { obj.notify(); } }
notify 的一种结果
1 2 3 4 20:00:53.096 [Thread-0] c.TestWaitNotify - 执行.... 20:00:53.099 [Thread-1] c.TestWaitNotify - 执行.... 20:00:55.096 [main] c.TestWaitNotify - 唤醒 obj 上其它线程 20:00:55.096 [Thread-0] c.TestWaitNotify - 其它代码....
notifyAll 的结果
1 2 3 4 5 19:58:15.457 [Thread-0] c.TestWaitNotify - 执行.... 19:58:15.460 [Thread-1] c.TestWaitNotify - 执行.... 19:58:17.456 [main] c.TestWaitNotify - 唤醒 obj 上其它线程 19:58:17.456 [Thread-1] c.TestWaitNotify - 其它代码.... 19:58:17.456 [Thread-0] c.TestWaitNotify - 其它代码....
wait() 方法会释放对象的锁,进入 WaitSet 等待区,从而让其他线程就机会获取对象的锁。无限制等待,直到 notify 为止wait(long n) 有时限的等待, 到 n 毫秒后结束等待,或是被 notify
4.8 wait notify 的正确姿势 开始之前先看看
sleep(long n) 和 wait(long n) 的区别
sleep 是 Thread 方法,而 wait 是 Object 的方法
sleep 不需要强制和 synchronized 配合使用,但 wait 需要 和 synchronized 一起用
sleep 在睡眠的同时,不会释放对象锁的,但 wait 在等待的时候会释放对象锁
它们 状态 TIMED_WAITING
step 1 1 2 3 static final Object room = new Object ();static boolean hasCigarette = false ;static boolean hasTakeout = false ;
思考下面的解决方案好不好,为什么?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 new Thread (() -> { synchronized (room) { log.debug("有烟没?[{}]" , hasCigarette); if (!hasCigarette) { log.debug("没烟,先歇会!" ); sleep(2 ); } log.debug("有烟没?[{}]" , hasCigarette); if (hasCigarette) { log.debug("可以开始干活了" ); } } }, "小南" ).start(); for (int i = 0 ; i < 5 ; i++) { new Thread (() -> { synchronized (room) { log.debug("可以开始干活了" ); } }, "其它人" ).start(); } sleep(1 ); new Thread (() -> { hasCigarette = true ; log.debug("烟到了噢!" ); }, "送烟的" ).start();
输出
1 2 3 4 5 6 7 8 9 10 20:49:49.883 [小南] c.TestCorrectPosture - 有烟没?[false ] 20:49:49.887 [小南] c.TestCorrectPosture - 没烟,先歇会! 20:49:50.882 [送烟的] c.TestCorrectPosture - 烟到了噢! 20:49:51.887 [小南] c.TestCorrectPosture - 有烟没?[true ] 20:49:51.887 [小南] c.TestCorrectPosture - 可以开始干活了 20:49:51.887 [其它人] c.TestCorrectPosture - 可以开始干活了 20:49:51.887 [其它人] c.TestCorrectPosture - 可以开始干活了 20:49:51.888 [其它人] c.TestCorrectPosture - 可以开始干活了 20:49:51.888 [其它人] c.TestCorrectPosture - 可以开始干活了 20:49:51.888 [其它人] c.TestCorrectPosture - 可以开始干活了
其它干活的线程,都要一直阻塞,效率太低
小南线程必须睡足 2s 后才能醒来,就算烟提前送到,也无法立刻醒来
加了 synchronized (room) 后,就好比小南在里面反锁了门睡觉,烟根本没法送进门,main 没加 synchronized 就好像 main 线程是翻窗户进来的
解决方法,使用 wait - notify 机制
step 2 思考下面的实现行吗,为什么?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 new Thread (() -> { synchronized (room) { log.debug("有烟没?[{}]" , hasCigarette); if (!hasCigarette) { log.debug("没烟,先歇会!" ); try { room.wait(2000 ); } catch (InterruptedException e) { e.printStackTrace(); } } log.debug("有烟没?[{}]" , hasCigarette); if (hasCigarette) { log.debug("可以开始干活了" ); } } }, "小南" ).start(); for (int i = 0 ; i < 5 ; i++) { new Thread (() -> { synchronized (room) { log.debug("可以开始干活了" ); } }, "其它人" ).start(); } sleep(1 ); new Thread (() -> { synchronized (room) { hasCigarette = true ; log.debug("烟到了噢!" ); room.notify(); } }, "送烟的" ).start();
输出:
1 2 3 4 5 6 7 8 9 10 11 13:09:38.156 c.TestCorrectPosture [小南] - 有烟没?[false] 13:09:38.158 c.TestCorrectPosture [小南] - 没烟,先歇会! 13:09:38.158 c.TestCorrectPosture [其它人] - 可以开始干活了 13:09:38.159 c.TestCorrectPosture [其它人] - 可以开始干活了 13:09:38.159 c.TestCorrectPosture [其它人] - 可以开始干活了 13:09:38.159 c.TestCorrectPosture [其它人] - 可以开始干活了 13:09:38.159 c.TestCorrectPosture [其它人] - 可以开始干活了 13:09:39.162 c.TestCorrectPosture [送烟的] - 烟到了噢! 13:09:39.163 c.TestCorrectPosture [小南] - 有烟没?[true] 13:09:39.163 c.TestCorrectPosture [小南] - 可以开始干活了
解决了其它干活的线程阻塞的问题
但如果有其它线程也在等待条件呢?
room.notify(); 是否会错误的唤醒其他线程
step 3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 new Thread (() -> { synchronized (room) { log.debug("有烟没?[{}]" , hasCigarette); if (!hasCigarette) { log.debug("没烟,先歇会!" ); try { room.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } log.debug("有烟没?[{}]" , hasCigarette); if (hasCigarette) { log.debug("可以开始干活了" ); } else { log.debug("没干成活..." ); } } }, "小南" ).start(); new Thread (() -> { synchronized (room) { Thread thread = Thread.currentThread(); log.debug("外卖送到没?[{}]" , hasTakeout); if (!hasTakeout) { log.debug("没外卖,先歇会!" ); try { room.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } log.debug("外卖送到没?[{}]" , hasTakeout); if (hasTakeout) { log.debug("可以开始干活了" ); } else { log.debug("没干成活..." ); } } }, "小女" ).start(); sleep(1 ); new Thread (() -> { synchronized (room) { hasTakeout = true ; log.debug("外卖到了噢!" ); room.notify(); } }, "送外卖的" ).start();
输出
1 2 3 4 5 6 7 20:53:12.173 [小南] c.TestCorrectPosture - 有烟没?[false ] 20:53:12.176 [小南] c.TestCorrectPosture - 没烟,先歇会! 20:53:12.176 [小女] c.TestCorrectPosture - 外卖送到没?[false ] 20:53:12.176 [小女] c.TestCorrectPosture - 没外卖,先歇会! 20:53:13.174 [送外卖的] c.TestCorrectPosture - 外卖到了噢! 20:53:13.174 [小南] c.TestCorrectPosture - 有烟没?[false ] 20:53:13.174 [小南] c.TestCorrectPosture - 没干成活...
notify 只能随机唤醒一个 WaitSet 中的线程,这时如果有其它线程也在等待,那么就可能唤醒不了正确的线 程,称之为【虚假唤醒】
解决方法,改为 notifyAll
step 4 1 2 3 4 5 6 7 new Thread (() -> { synchronized (room) { hasTakeout = true ; log.debug("外卖到了噢!" ); room.notifyAll(); } }, "送外卖的" ).start();
输出
1 2 3 4 5 6 7 8 9 20:55:23.978 [小南] c.TestCorrectPosture - 有烟没?[false ] 20:55:23.982 [小南] c.TestCorrectPosture - 没烟,先歇会! 20:55:23.982 [小女] c.TestCorrectPosture - 外卖送到没?[false ] 20:55:23.982 [小女] c.TestCorrectPosture - 没外卖,先歇会! 20:55:24.979 [送外卖的] c.TestCorrectPosture - 外卖到了噢! 20:55:24.979 [小女] c.TestCorrectPosture - 外卖送到没?[true ] 20:55:24.980 [小女] c.TestCorrectPosture - 可以开始干活了 20:55:24.980 [小南] c.TestCorrectPosture - 有烟没?[false ] 20:55:24.980 [小南] c.TestCorrectPosture - 没干成活...
用 notifyAll 仅解决某个线程的唤醒问题,但使用 if + wait 判断仅有一次机会,一旦条件不成立,就没有重新判断的机会了
解决方法,用 while + wait,当条件不成立,再次 wait
step 5 将 if 改为 while
1 2 3 4 5 6 7 8 if (!hasCigarette) { log.debug("没烟,先歇会!" ); try { room.wait(); } catch (InterruptedException e) { e.printStackTrace(); } }
改动后
1 2 3 4 5 6 7 8 while (!hasCigarette) { log.debug("没烟,先歇会!" ); try { room.wait(); } catch (InterruptedException e) { e.printStackTrace(); } }
输出
1 2 3 4 5 6 7 8 20:58:34.322 [小南] c.TestCorrectPosture - 有烟没?[false ] 20:58:34.326 [小南] c.TestCorrectPosture - 没烟,先歇会! 20:58:34.326 [小女] c.TestCorrectPosture - 外卖送到没?[false ] 20:58:34.326 [小女] c.TestCorrectPosture - 没外卖,先歇会! 20:58:35.323 [送外卖的] c.TestCorrectPosture - 外卖到了噢! 20:58:35.324 [小女] c.TestCorrectPosture - 外卖送到没?[true ] 20:58:35.324 [小女] c.TestCorrectPosture - 可以开始干活了 20:58:35.324 [小南] c.TestCorrectPosture - 没烟,先歇会!
1 2 3 4 5 6 7 8 9 10 synchronized (lock) { while (条件不成立) { lock.wait(); } } synchronized (lock) { lock.notifyAll(); }
最终版本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 @Slf4j(topic = "c.TestCorrectPosture") public class TestCorrectPostureStep5 { static final Object room = new Object (); static boolean hasCigarette = false ; static boolean hasTakeout = false ; public static void main (String[] args) { new Thread (() -> { synchronized (room) { log.debug("有烟没?[{}]" , hasCigarette); while (!hasCigarette) { log.debug("没烟,先歇会!" ); try { room.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } log.debug("有烟没?[{}]" , hasCigarette); if (hasCigarette) { log.debug("可以开始干活了" ); } else { log.debug("没干成活..." ); } } }, "小南" ).start(); new Thread (() -> { synchronized (room) { Thread thread = Thread.currentThread(); log.debug("外卖送到没?[{}]" , hasTakeout); while (!hasTakeout) { log.debug("没外卖,先歇会!" ); try { room.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } log.debug("外卖送到没?[{}]" , hasTakeout); if (hasTakeout) { log.debug("可以开始干活了" ); } else { log.debug("没干成活..." ); } } }, "小女" ).start(); sleep(1 ); new Thread (() -> { synchronized (room) { hasTakeout = true ; log.debug("外卖到了噢!" ); room.notifyAll(); } }, "送外卖的" ).start(); } }
* 同步模式之保护性暂停 1.定义 即 Guarded Suspension,用在一个线程等待另一个线程的执行结果 要点
有一个结果需要从一个线程传递到另一个线程,让他们关联同一个 GuardedObject
如果有结果不断从一个线程到另一个线程那么可以使用消息队列(见生产者/消费者)
JDK 中,join 的实现、Future 的实现,采用的就是此模式
因为要等待另一方的结果,因此归类到同步模式
2.实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class GuardedObject { private Object response; private final Object lock = new Object (); public Object get () { synchronized (lock) { while (response == null ) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } return response; } } public void complete (Object response) { synchronized (lock) { this .response = response; lock.notifyAll(); } } }
测试 一个线程等待另一个线程的执行结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 @Override public void run () { GuardedObject guardedObject = MailBoxes.getGuardedObject(id); guardedObject.set(mail); log.debug("送信成功,id={},内容:{}" ,id,mail); public static void main (String[] args) { GuardedObject guardedObject = new GuardedObject (); new Thread (() -> { try { List<String> response = download(); log.debug("download complete..." ); guardedObject.complete(response); } catch (IOException e) { e.printStackTrace(); } }).start(); log.debug("waiting..." ); Object response = guardedObject.get(); log.debug("get response: [{}] lines" , ((List<String>) response).size()); }
执行结果
1 2 3 08:42:18.568 [main] c.TestGuardedObject - waiting... 08:42:23.312 [Thread-0] c.TestGuardedObject - download complete... 08:42:23.312 [main] c.TestGuardedObject - get response: [3] lines
3.带超时版 GuardedObject 如果要控制超时时间呢
long waitTime = millis - timePassed; 防止虚假唤醒要多等时间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 class GuardedObjectV2 { private Object response; private final Object lock = new Object (); public Object get (long timeout) { synchronized (this ) { long begin = System.currentTimeMillis(); long passedTime = 0 ; while (response == null ) { long waitTime = timeout - passedTime; if (timeout - passedTime <= 0 ) { break ; } try { this .wait(waitTime); } catch (InterruptedException e) { e.printStackTrace(); } passedTime = System.currentTimeMillis() - begin; } return response; } } public void complete (Object response) { synchronized (this ) { this .response = response; this .notifyAll(); } } }
测试,没有超时
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public static void main (String[] args) { GuardedObjectV2 v2 = new GuardedObjectV2 (); new Thread (() -> { sleep(1 ); v2.complete(null ); sleep(1 ); v2.complete(Arrays.asList("a" , "b" , "c" )); }).start(); Object response = v2.get(2500 ); if (response != null ) { log.debug("get response: [{}] lines" , ((List<String>) response).size()); } else { log.debug("can't get response" ); } }
输出
1 2 3 4 5 6 7 08:49:39.917 [main] c.GuardedObjectV2 - waitTime: 2500 08:49:40.917 [Thread-0] c.GuardedObjectV2 - notify... 08:49:40.917 [main] c.GuardedObjectV2 - timePassed: 1003, object is null true 08:49:40.917 [main] c.GuardedObjectV2 - waitTime: 1497 08:49:41.918 [Thread-0] c.GuardedObjectV2 - notify... 08:49:41.918 [main] c.GuardedObjectV2 - timePassed: 2004, object is null false 08:49:41.918 [main] c.TestGuardedObjectV2 - get response: [3] lines
测试超时
1 2 List<String> lines = v2.get(1500 );
输出
1 2 3 4 5 6 7 8 9 08:47 :54.963 [main] c.GuardedObjectV2 - waitTime: 1500 08:47 :55.963 [Thread-0 ] c.GuardedObjectV2 - notify... 08:47 :55.963 [main] c.GuardedObjectV2 - timePassed: 1002 , object is null true 08:47 :55.963 [main] c.GuardedObjectV2 - waitTime: 498 08:47 :56.461 [main] c.GuardedObjectV2 - timePassed: 1500 , object is null true 08:47 :56.461 [main] c.GuardedObjectV2 - waitTime: 0 08:47 :56.461 [main] c.GuardedObjectV2 - break ... 08:47 :56.461 [main] c.TestGuardedObjectV2 - can't get response 08:47:56.963 [Thread-0] c.GuardedObjectV2 - notify...
* 原理之 join 是调用者轮询检查线程 alive 状态
等价于下面的代码
1 2 3 4 5 6 synchronized (t1) { while (t1.isAlive()) { t1.wait(0 ); } }
注意
join 体现的是【保护性暂停】模式,请参考之
源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 public final void join () throws InterruptedException { join(0 ); } public final synchronized void join (long millis) throws InterruptedException { long base = System.currentTimeMillis(); long now = 0 ; if (millis < 0 ) { throw new IllegalArgumentException ("timeout value is negative" ); } if (millis == 0 ) { while (isAlive()) { wait(0 ); } } else { while (isAlive()) { long delay = millis - now; if (delay <= 0 ) { break ; } wait(delay); now = System.currentTimeMillis() - base; } } }
4.多任务版GuardedObject 图中 Futures 就好比居民楼一层的信箱(每个信箱有房间编号),左侧的 t0,t2,t4 就好比等待邮件的居民,右 侧的 t1,t3,t5 就好比邮递员 。
如果需要在多个类之间使用 GuardedObject 对象,作为参数传递不是很方便,因此设计一个用来解耦的中间类, 这样不仅能够解耦【结果等待者】和【结果生产者】,还能够同时支持多个任务的管理。
新增 id 用来标识 Guarded Object
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 class GuardedObject { private int id public GuardedObject (int id) { this .id = id; } public int getId () { return id; } private Object response; public Object get (long timeout) { synchronized (this ) { long begin = System.currentTimeMillis(); long passedTime = 0 ; while (response == null ) { long waitTime = timeout - passedTime; if (timeout - passedTime <= 0 ) { break ; } try { this .wait(waitTime); } catch (InterruptedException e) { e.printStackTrace(); } passedTime = System.currentTimeMillis() - begin; } return response; } } public void complete (Object response) { synchronized (this ) { this .response = response; this .notifyAll(); } } }
中间解耦类(重点)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class Mailboxes { private static Map<Integer, GuardedObject> boxes = new Hashtable <>(); private static int id = 1 ; private static synchronized int generateId () { return id++; } public static GuardedObject getGuardedObject (int id) { return boxes.remove(id); } public static GuardedObject createGuardedObject () { GuardedObject go = new GuardedObject (generateId()); boxes.put(go.getId(), go); return go; } public static Set<Integer> getIds () { return boxes.keySet(); } }
业务相关类
1 2 3 4 5 6 7 8 9 10 class People extends Thread { @Override public void run () { GuardedObject guardedObject = Mailboxes.createGuardedObject(); log.debug("开始收信 id:{}" , guardedObject.getId()); Object mail = guardedObject.get(5000 ); log.debug("收到信 id:{}, 内容:{}" , guardedObject.getId(), mail); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Postman extends Thread { private int id; private String mail; public Postman (int id, String mail) { this .id = id; this .mail = mail; } @Override public void run () { GuardedObject guardedObject = Mailboxes.getGuardedObject(id); log.debug("送信 id:{}, 内容:{}" , id, mail); guardedObject.complete(mail); } }
测试
1 2 3 4 5 6 7 8 9 public static void main (String[] args) throws InterruptedException { for (int i = 0 ; i < 3 ; i++) { new People ().start(); } Sleeper.sleep(1 ); for (Integer id : Mailboxes.getIds()) { new Postman (id, "内容" + id).start(); } }
某次运行结果
1 2 3 4 5 6 7 8 9 10 :35 :05.689 c.People [Thread-1 ] - 开始收信 id:3 10 :35 :05.689 c.People [Thread-2 ] - 开始收信 id:1 10 :35 :05.689 c.People [Thread-0 ] - 开始收信 id:2 10 :35 :06.688 c.Postman [Thread-4 ] - 送信 id:2 , 内容:内容2 10 :35 :06.688 c.Postman [Thread-5 ] - 送信 id:1 , 内容:内容1 10 :35 :06.688 c.People [Thread-0 ] - 收到信 id:2 , 内容:内容2 10 :35 :06.688 c.People [Thread-2 ] - 收到信 id:1 , 内容:内容1 10 :35 :06.688 c.Postman [Thread-3 ] - 送信 id:3 , 内容:内容3 10 :35 :06.689 c.People [Thread-1 ] - 收到信 id:3 , 内容:内容3
异步模式之生产者消费者 1.定义 要点
与前面的保护性暂停中的 GuardObject 不同,不需要产生结果和消费结果的线程一一对应
消费队列可以用来平衡生产和消费的线程资源
生产者仅负责产生结果数据,不关心数据该如何处理,而消费者专心处理结果数据
消息队列是有容量限制的,满时不会再加入数据,空时不会再消耗数据
JDK 中各种阻塞队列,采用的就是这种模式
2.实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 class Message { private int id; private Object message; public Message (int id, Object message) { this .id = id; this .message = message; } public int getId () { return id; } public Object getMessage () { return message; } } class MessageQueue { private LinkedList<Message> queue; private int capacity; public MessageQueue (int capacity) { this .capacity = capacity; queue = new LinkedList <>(); } public Message take () { synchronized (queue) { while (queue.isEmpty()) { log.debug("没货了, wait" ); try { queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Message message = queue.removeFirst(); queue.notifyAll(); return message; } } public void put (Message message) { synchronized (queue) { while (queue.size() == capacity) { log.debug("库存已达上限, wait" ); try { queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } queue.addLast(message); queue.notifyAll(); } } }
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 MessageQueue messageQueue = new MessageQueue (2 );for (int i = 0 ; i < 4 ; i++) { int id = i; new Thread (() -> { try { log.debug("download..." ); List<String> response = Downloader.download(); log.debug("try put message({})" , id); messageQueue.put(new Message (id, response)); } catch (IOException e) { e.printStackTrace(); } }, "生产者" + i).start(); } new Thread (() -> { while (true ) { Message message = messageQueue.take(); List<String> response = (List<String>) message.getMessage(); log.debug("take message({}): [{}] lines" , message.getId(), response.size()); } }, "消费者" ).start();
某次运行结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 10:48:38.070 [生产者3] c.TestProducerConsumer - download... 10:48:38.070 [生产者0] c.TestProducerConsumer - download... 10:48:38.070 [消费者] c.MessageQueue - 没货了, wait 10:48:38.070 [生产者1] c.TestProducerConsumer - download... 10:48:38.070 [生产者2] c.TestProducerConsumer - download... 10:48:41.236 [生产者1] c.TestProducerConsumer - try put message(1) 10:48:41.237 [生产者2] c.TestProducerConsumer - try put message(2) 10:48:41.236 [生产者0] c.TestProducerConsumer - try put message(0) 10:48:41.237 [生产者3] c.TestProducerConsumer - try put message(3) 10:48:41.239 [生产者2] c.MessageQueue - 库存已达上限, wait 10:48:41.240 [生产者1] c.MessageQueue - 库存已达上限, wait 10:48:41.240 [消费者] c.TestProducerConsumer - take message(0): [3] lines 10:48:41.240 [生产者2] c.MessageQueue - 库存已达上限, wait 10:48:41.240 [消费者] c.TestProducerConsumer - take message(3): [3] lines 10:48:41.240 [消费者] c.TestProducerConsumer - take message(1): [3] lines 10:48:41.240 [消费者] c.TestProducerConsumer - take message(2): [3] lines 10:48:41.240 [消费者] c.MessageQueue - 没货了, wait
结果解读
4.9 Park & Unpark 基本使用 它们是 LockSupport 类中的方法
1 2 3 4 LockSupport.park(); LockSupport.unpark(暂停线程对象)
先 park 再 unpark
1 2 3 4 5 6 7 8 9 10 11 12 Thread t1 = new Thread (() -> { log.debug("start..." ); sleep(1 ); log.debug("park..." ); LockSupport.park(); log.debug("resume..." ); },"t1" ); t1.start(); sleep(2 ); log.debug("unpark..." ); LockSupport.unpark(t1);
输出
1 2 3 4 18:42:52.585 c.TestParkUnpark [t1] - start... 18:42:53.589 c.TestParkUnpark [t1] - park... 18:42:54.583 c.TestParkUnpark [main] - unpark... 18:42:54.583 c.TestParkUnpark [t1] - resume...
先 unpark 再 park
1 2 3 4 5 6 7 8 9 10 11 12 Thread t1 = new Thread (() -> { log.debug("start..." ); sleep(2 ); log.debug("park..." ); LockSupport.park(); log.debug("resume..." ); }, "t1" ); t1.start sleep (1 ) ;log.debug("unpark..." ); LockSupport.unpark(t1);
输出
子线程休息2s
主线程1s后unpark,子线程并没有立刻恢复
1 2 3 4 18:43:50.765 c.TestParkUnpark [t1] - start... 18:43:51.764 c.TestParkUnpark [main] - unpark... 18:43:52.769 c.TestParkUnpark [t1] - park... 18:43:52.769 c.TestParkUnpark [t1] - resume...
特点 与 Object 的 wait & notify 相比
wait,notify 和 notifyAll 必须配合 Object Monitor 一起使用,而 park,unpark 不必
park & unpark 是以线程为单位来【阻塞】和【唤醒】线程,而 notify 只能随机唤醒一个等待线程,notifyAll 是唤醒所有等待线程,就不那么【精确】
park & unpark 可以先 unpark,而 wait & notify 不能先 notify
* 原理之park和unpark 每个线程都有自己的一个 Parker 对象(由C++编写,java中不可见),由三部分组成 _counter , _cond 和 _mutex 打个比喻
线程就像一个旅人,Parker 就像他随身携带的背包,条件变量就好比背包中的帐篷。_counter 就好比背包中 的备用干粮(0 为耗尽,1 为充足)
调用 park 就是要看需不需要停下来歇息
如果备用干粮耗尽,那么钻进帐篷歇息
如果备用干粮充足,那么不需停留,继续前进
调用 unpark,就好比令干粮充足
如果这时线程还在帐篷,就唤醒让他继续前进
如果这时线程还在运行,那么下次他调用 park 时,仅是消耗掉备用干粮,不需停留继续前进
因为背包空间有限,多次调用 unpark 仅会补充一份备用干粮
当counter为0,调用park才会停下
当前线程调用 Unsafe.park() 方法
检查 _counter ,本情况为 0,这时,获得 _mutex 互斥锁
线程进入 _cond 条件变量阻塞
设置 _counter = 0
调用 Unsafe.unpark(Thread_0) 方法,设置 _counter 为 1
唤醒 _cond 条件变量中的 Thread_0
Thread_0 恢复运行
设置 _counter 为 0
调用 Unsafe.unpark(Thread_0) 方法,设置 _counter 为 1
当前线程调用 Unsafe.park() 方法
检查 _counter ,本情况为 1,这时线程无需阻塞,继续运行
设置 _counter 为 0
4.10 重新理解线程状态转换
假设有线程 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 public class TestWaitNotify { final static Object obj = new Object (); public static void main (String[] args) { new Thread (() -> { synchronized (obj) { log.debug("执行...." ); try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } log.debug("其它代码...." ); } },"t1" ).start(); new Thread (() -> { synchronized (obj) { log.debug("执行...." ); try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } log.debug("其它代码...." ); } },"t2" ).start(); sleep(0.5 ); log.debug("唤醒 obj 上其它线程" ); synchronized (obj) { obj.notifyAll(); } } }
情况 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 2 3 4 5 6 7 8 9 10 11 12 13 14 class BigRoom { public void sleep () { synchronized (this ) { log.debug("sleeping 2 小时" ); Sleeper.sleep(2 ); } } public void study () { synchronized (this ) { log.debug("study 1 小时" ); Sleeper.sleep(1 ); } } }
执行
1 2 3 4 5 6 7 8 BigRoom bigRoom = new BigRoom ();new Thread (() -> { bigRoom.compute(); },"小南" ).start(); new Thread (() -> { bigRoom.sleep(); },"小女" ).start();
结果
1 2 12:13:54.471 [小南] c.BigRoom - study 1 小时 12:13:55.476 [小女] c.BigRoom - sleeping 2 小时
改进
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class BigRoom { private final Object studyRoom = new Object (); private final Object bedRoom = new Object (); public void sleep () { synchronized (bedRoom) { log.debug("sleeping 2 小时" ); Sleeper.sleep(2 ); } } public void study () { synchronized (studyRoom) { log.debug("study 1 小时" ); Sleeper.sleep(1 ); } } }
某次执行结果
1 2 12:15:35.069 [小南] c.BigRoom - study 1 小时 12:15:35.069 [小女] c.BigRoom - sleeping 2 小时
将锁的粒度细分
好处,是可以增强并发度
坏处,如果一个线程需要同时获得多把锁,就容易发生死锁
前提:两把锁锁住的两段代码互不相关
4.12 活跃性
死锁 有这样的情况:一个线程需要同时获取多把锁,这时就容易发生死锁
t1 线程 获得 A对象 锁,接下来想获取 B对象 的锁
t2 线程 获得 B对象 锁,接下来想获取 A对象 的锁 例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 @Slf4j(topic = "c.TestDeadLock") public class TestDeadLock { public static void main (String[] args) { test1(); } private static void test1 () { Object A = new Object (); Object B = new Object (); Thread t1 = new Thread (() -> { synchronized (A) { log.debug("lock A" ); sleep(1 ); synchronized (B) { log.debug("lock B" ); log.debug("操作..." ); } } }, "t1" ); Thread t2 = new Thread (() -> { synchronized (B) { log.debug("lock B" ); sleep(0.5 ); synchronized (A) { log.debug("lock A" ); log.debug("操作..." ); } } }, "t2" ); t1.start(); t2.start(); } }
结果
1 2 12:22:06.962 [t2] c.TestDeadLock - lock B 12:22:06.962 [t1] c.TestDeadLock - lock A
解决方式:
定位死锁
检测死锁可以使用 jconsole工具,或者使用 jps 定位进程 id,再用 jstack 定位死锁:
1 2 3 4 5 6 7 cmd > jps Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8 12320 Jps 22816 KotlinCompileDaemon 33200 TestDeadLock // JVM 进程 11508 Main 28468 Launcher
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 cmd > jstack 33200 Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8 2018-12-29 05:51:40 Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.91-b14 mixed mode): "DestroyJavaVM" [0x0000000000000000] java.lang.Thread.State: RUNNABLE "Thread-1" [0x000000001f54f000] java.lang.Thread.State: BLOCKED (on object monitor) at thread.TestDeadLock.lambda$main$1 (TestDeadLock.java:28) - waiting to lock <0x000000076b5bf1c0> (a java.lang.Object) - locked <0x000000076b5bf1d0> (a java.lang.Object) at thread.TestDeadLock$$Lambda$2 /883049899.run(Unknown Source) at java.lang.Thread.run(Thread.java:745) "Thread-0" [0x000000001f44f000] java.lang.Thread.State: BLOCKED (on object monitor) at thread.TestDeadLock.lambda$main$0 (TestDeadLock.java:15) - waiting to lock <0x000000076b5bf1d0> (a java.lang.Object) - locked <0x000000076b5bf1c0> (a java.lang.Object) at thread.TestDeadLock$$Lambda$1 /495053715.run(Unknown Source) at java.lang.Thread.run(Thread.java:745) // 略去部分输出 Found one Java-level deadlock: ============================= "Thread-1" : waiting to lock monitor 0x000000000361d378 (object 0x000000076b5bf1c0, a java.lang.Object), which is held by "Thread-0" "Thread-0" : waiting to lock monitor 0x000000000361e768 (object 0x000000076b5bf1d0, a java.lang.Object), which is held by "Thread-1" Java stack information for the threads listed above: =================================================== "Thread-1" : at thread.TestDeadLock.lambda$main$1 (TestDeadLock.java:28) - waiting to lock <0x000000076b5bf1c0> (a java.lang.Object) - locked <0x000000076b5bf1d0> (a java.lang.Object) at thread.TestDeadLock$$Lambda$2 /883049899.run(Unknown Source) at java.lang.Thread.run(Thread.java:745) "Thread-0" : at thread.TestDeadLock.lambda$main$0 (TestDeadLock.java:15) - waiting to lock <0x000000076b5bf1d0> (a java.lang.Object) - locked <0x000000076b5bf1c0> (a java.lang.Object) at thread.TestDeadLock$$Lambda$1 /495053715.run(Unknown Source) at java.lang.Thread.run(Thread.java:745) Found 1 deadlock.
可以使用 jconsole图形界面
避免死锁要注意加锁顺序
另外如果由于某个线程进入了死循环,导致其它线程一直等待,对于这种情况 linux 下可以通过 top 先定位到 CPU 占用高的 Java 进程,再利用 top -Hp 进程id 来定位是哪个线程,最后再用 jstack 排查
哲学家就餐问题 代码 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 public class TestDeadLock { public static void main (String[] args) { Chopstick c1 = new Chopstick ("1" ); Chopstick c2 = new Chopstick ("2" ); Chopstick c3 = new Chopstick ("3" ); Chopstick c4 = new Chopstick ("4" ); Chopstick c5 = new Chopstick ("5" ); new Philosopher ("苏格拉底" , c1, c2).start(); new Philosopher ("柏拉图" , c2, c3).start(); new Philosopher ("亚里士多德" , c3, c4).start(); new Philosopher ("赫拉克利特" , c4, c5).start(); new Philosopher ("阿基米德" , c5, c1).start(); } } @Slf4j(topic = "c.Philosopher") class Philosopher extends Thread { Chopstick left; Chopstick right; public Philosopher (String name, Chopstick left, Chopstick right) { super (name); this .left = left; this .right = right; } @Override public void run () { while (true ) { synchronized (right) { eat(); } } } } Random random = new Random (); private void eat () { log.debug("eating..." ); Sleeper.sleep(0.5 ); } } class Chopstick { String name; public Chopstick (String name) { this .name = name; } @Override public String toString () { return "筷子{" + name + '}' ; } }
jconsole发现五个线程均陷入死锁:
活锁
活锁出现在两个线程互相改变对方的结束条件,最后谁也无法结束,例如
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public class TestLiveLock { static volatile int count = 10 ; static final Object lock = new Object (); public static void main (String[] args) { new Thread (() -> { while (count > 0 ) { sleep(0.2 ); count--; log.debug("count: {}" , count); } }, "t1" ).start(); new Thread (() -> { while (count < 20 ) { sleep(0.2 ); count++; log.debug("count: {}" , count); } }, "t2" ).start(); } }
解决方式:
错开线程的运行时间,使得一方不能改变另一方的结束条件。
将睡眠时间调整为随机数。
饥饿
1 2 3 4 5 new Philosopher ("苏格拉底" , c1, c2).start(); new Philosopher ("柏拉图" , c2, c3).start(); new Philosopher ("亚里士多德" , c3, c4).start(); new Philosopher ("赫拉克利特" , c4, c5).start(); new Philosopher ("阿基米德" , c1, c5).start();
说明:
顺序加锁可以解决死锁问题,但也会导致一些线程一直得不到锁,产生饥饿现象。
解决方式:ReentrantLock
4.13 ReentrantLock (可重入锁) 相对于 synchronized 它具备如下特点
可中断
可以设置超时时间
可以设置为公平锁 :先来后到
支持多个条件变量 :相当于多个waitset 与 synchronized 一样,都支持可重入 基本语法
reentrantLock.lock(); 可放在try外面或者里面都行
1 2 3 4 5 6 7 8 reentrantLock.lock(); try { } finally { reentrantLock.unlock(); }
可重入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 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(); } }
输出
1 2 3 17:59:11.862 [main] c.TestReentrant - execute method1 17:59:11.865 [main] c.TestReentrant - execute method2 17:59:11.865 [main] c.TestReentrant - execute method3
可打断
可打断指的是处于阻塞状态等待锁的线程可以被打断等待。
注意lock.lockInterruptibly()和lock.trylock()方法是可打断的,lock.lock()不是。
可打断的意义在于避免得不到锁的线程无限制地等待下去,防止死锁的一种方式。
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 ReentrantLock lock = new ReentrantLock ();Thread t1 = new Thread (() -> { log.debug("启动..." ); try { lock.lockInterruptibly(); } catch (InterruptedException e) { e.printStackTrace(); log.debug("等锁的过程中被打断" ); return ; } try { log.debug("获得了锁" ); } finally { lock.unlock(); } }, "t1" ); lock.lock(); log.debug("获得了锁" ); t1.start(); try { sleep(1 ); t1.interrupt(); log.debug("执行打断" ); } finally { lock.unlock(); }
输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 18:02:40.520 [main] c.TestInterrupt - 获得了锁 18:02:40.524 [t1] c.TestInterrupt - 启动... 18:02:41.530 [main] c.TestInterrupt - 执行打断 java.lang.InterruptedException at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireInterruptibly(AbstractQueuedSynchr onizer.java:898) at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly(AbstractQueuedSynchron izer.java:1222) at java.util.concurrent.locks.ReentrantLock.lockInterruptibly(ReentrantLock.java:335) at cn.itcast.n4.reentrant.TestInterrupt.lambda$main$0 (TestInterrupt.java:17) at java.lang.Thread.run(Thread.java:748) 18:02:41.532 [t1] c.TestInterrupt - 等锁的过程中被打断
注意如果是不可中断模式,那么即使使用了 interrupt 也不会让等待中断
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 ReentrantLock lock = new ReentrantLock ();Thread t1 = new Thread (() -> { log.debug("启动..." ); lock.lock(); try { log.debug("获得了锁" ); } finally { lock.unlock(); } }, "t1" ); lock.lock(); log.debug("获得了锁" ); t1.start(); try { sleep(1 ); t1.interrupt(); log.debug("执行打断" ); sleep(1 ); } finally { log.debug("释放了锁" ); lock.unlock(); }
输出
1 2 3 4 5 18:06:56.261 [main] c.TestInterrupt - 获得了锁 18:06:56.265 [t1] c.TestInterrupt - 启动... 18:06:57.266 [main] c.TestInterrupt - 执行打断 // 这时 t1 并没有被真正打断, 而是仍继续等待锁 18:06:58.267 [main] c.TestInterrupt - 释放了锁 18:06:58.267 [t1] c.TestInterrupt - 获得了锁
锁超时 立刻失败
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ReentrantLock lock = new ReentrantLock ();Thread t1 = new Thread (() -> { log.debug("启动..." ); if (!lock.tryLock()) { log.debug("获取立刻失败,返回" ); return ; } try { log.debug("获得了锁" ); } finally { lock.unlock(); } }, "t1" ); lock.lock(); log.debug("获得了锁" ); t1.start(); try { sleep(2 ); } finally { lock.unlock(); }
输出
1 2 3 18:15:02.918 [main] c.TestTimeout - 获得了锁 18:15:02.921 [t1] c.TestTimeout - 启动... 18:15:02.921 [t1] c.TestTimeout - 获取立刻失败,返回
超时失败
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ReentrantLock lock = new ReentrantLock ();Thread t1 = new Thread (() -> { log.debug("启动..." ); try { if (!lock.tryLock(1 , TimeUnit.SECONDS)) { log.debug("获取等待 1s 后失败,返回" ); return ; } } catch (InterruptedException e) { e.printStackTrace(); } try { log.debug("获得了锁" ); } finally { lock.unlock(); } }, "t1" ); lock.lock(); log.debug("获得了锁" ); t1.start(); try { sleep(2 ); } finally { lock.unlock(); }
输出
1 2 3 18:19:40.537 [main] c.TestTimeout - 获得了锁 18:19:40.544 [t1] c.TestTimeout - 启动... 18:19:41.547 [t1] c.TestTimeout - 获取等待 1s 后失败,返回
使用 tryLock 解决哲学家就餐问题
1 2 3 4 5 6 7 8 9 10 class Chopstick extends ReentrantLock { String name; public Chopstick (String name) { this .name = name; } @Override public String toString () { return "筷子{" + name + '}' ; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 class Philosopher extends Thread { Chopstick left; Chopstick right; public Philosopher (String name, Chopstick left, Chopstick right) { super (name); this .left = left; this .right = right; } @Override public void run () { while (true ) { if (left.tryLock()) { try { if (right.tryLock()) { try { eat(); } finally { right.unlock(); } } } finally { left.unlock(); } } } } private void eat () { log.debug("eating..." ); Sleeper.sleep(1 ); } }
公平锁 ReentrantLock 默认是不公平的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ReentrantLock lock = new ReentrantLock (false );lock.lock(); for (int i = 0 ; i < 500 ; i++) { new Thread (() -> { lock.lock(); try { System.out.println(Thread.currentThread().getName() + " running..." ); } finally { lock.unlock(); } }, "t" + i).start(); } Thread.sleep(1000 ); new Thread (() -> { System.out.println(Thread.currentThread().getName() + " start..." ); lock.lock(); try { System.out.println(Thread.currentThread().getName() + " running..." ); } finally { lock.unlock(); } }, "强行插入" ).start(); lock.unlock();
强行插入,有机会在中间输出
注意 :该实验不一定总能复现
1 2 3 4 5 6 7 8 9 10 11 12 t39 running... t40 running... t41 running... t42 running... t43 running... 强行插入 start... 强行插入 running... t44 running... t45 running... t46 running... t47 running... t49 running...
改为公平锁后
1 ReentrantLock lock = new ReentrantLock (true );
强行插入,总是在最后输出
1 2 3 4 5 6 7 8 9 10 t465 running... t464 running... t477 running... t442 running... t468 running... t493 running... t482 running... t485 running... t481 running... 强行插入 running...
公平锁一般没有必要,会降低并发度,后面分析原理时会讲解
条件变量 synchronized 中也有条件变量,就是我们讲原理时那个 waitSet 休息室,当条件不满足时进入 waitSet 等待 ReentrantLock 的条件变量比 synchronized 强大之处在于,它是支持多个条件变量的,这就好比
synchronized 是那些不满足条件的线程都在一间休息室等消息
而 ReentrantLock 支持多间休息室,有专门等烟的休息室、专门等早餐的休息室、唤醒时也是按休息室来唤 醒
使用要点
await 前需要获得锁
await 执行后,会释放锁,进入 conditionObject 等待
await 的线程被唤醒(或打断、或超时)取重新竞争 lock 锁
竞争 lock 锁成功后,从 await 后继续执行
详细API 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 public interface Condition { void await () throws InterruptedException; void awaitUninterruptibly () ; long awaitNanos (long nanosTimeout) throws InterruptedException; boolean await (long time, TimeUnit unit) throws InterruptedException; boolean awaitUntil (Date deadline) throws InterruptedException; void signal () ; void signalAll () ; }
例子: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 @Slf4j(topic = "c.Test24") public class Test24 { static final Object room = new Object (); static boolean hasCigarette = false ; static boolean hasTakeout = false ; static ReentrantLock ROOM = new ReentrantLock (); static Condition waitCigaretteSet = ROOM.newCondition(); static Condition waitTakeoutSet = ROOM.newCondition(); public static void main (String[] args) { new Thread (() -> { ROOM.lock(); try { log.debug("有烟没?[{}]" , hasCigarette); while (!hasCigarette) { log.debug("没烟,先歇会!" ); try { waitCigaretteSet.await(); } catch (InterruptedException e) { e.printStackTrace(); } } log.debug("可以开始干活了" ); } finally { ROOM.unlock(); } }, "小南" ).start(); new Thread (() -> { ROOM.lock(); try { log.debug("外卖送到没?[{}]" , hasTakeout); while (!hasTakeout) { log.debug("没外卖,先歇会!" ); try { waitTakeoutSet.await(); } catch (InterruptedException e) { e.printStackTrace(); } } log.debug("可以开始干活了" ); } finally { ROOM.unlock(); } }, "小女" ).start(); sleep(1 ); new Thread (() -> { ROOM.lock(); try { hasTakeout = true ; waitTakeoutSet.signal(); } finally { ROOM.unlock(); } }, "送外卖的" ).start(); sleep(1 ); new Thread (() -> { ROOM.lock(); try { hasCigarette = true ; waitCigaretteSet.signal(); } finally { ROOM.unlock(); } }, "送烟的" ).start(); } }
输出
1 2 3 4 5 6 17:58:21.920 c.Test24 [小南] - 有烟没?[false ] 17:58:21.921 c.Test24 [小南] - 没烟,先歇会! 17:58:21.921 c.Test24 [小女] - 外卖送到没?[false ] 17:58:21.921 c.Test24 [小女] - 没外卖,先歇会! 17:58:22.926 c.Test24 [小女] - 可以开始干活了 17:58:23.927 c.Test24 [小南] - 可以开始干活了
* 同步模式之顺序控制 固定运行顺序 比如,必须先 2 后 1 打印
wait notify 版 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 @Slf4j(topic = "c.Test25") public class Test25 { static final Object lock = new Object (); static boolean t2runned = false ; public static void main (String[] args) { Thread t1 = new Thread (() -> { synchronized (lock) { while (!t2runned) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } log.debug("1" ); } }, "t1" ); Thread t2 = new Thread (() -> { synchronized (lock) { log.debug("2" ); t2runned = true ; lock.notifyAll(); } }, "t2" ); t1.start(); t2.start(); } }
Park Unpark 版 可以看到,实现上很麻烦:
首先,需要保证先 wait 再 notify,否则 wait 线程永远得不到唤醒。因此使用了『运行标记』来判断该不该 wait
第二,如果有些干扰线程错误地 notify 了 wait 线程,条件不满足时还要重新等待,使用了 while 循环来解决 此问题
最后,唤醒对象上的 wait 线程需要使用 notifyAll,因为『同步对象』上的等待线程可能不止一个 可以使用 LockSupport 类的 park 和 unpark 来简化上面的题目:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 @Slf4j(topic = "c.Test26") public class Test26 { public static void main (String[] args) { Thread t1 = new Thread (() -> { LockSupport.park(); log.debug("1" ); }, "t1" ); t1.start(); new Thread (() -> { log.debug("2" ); LockSupport.unpark(t1); },"t2" ).start(); } } Thread t1 = new Thread (() -> { try { Thread.sleep(1000 ); } catch (InterruptedException e) { } LockSupport.park(); System.out.println("1" ); }); Thread t2 = new Thread (() -> { System.out.println("2" ); LockSupport.unpark(t1); }); t1.start(); t2.start();
park 和 unpark 方法比较灵活,他俩谁先调用,谁后调用无所谓。并且是以线程为单位进行『暂停』和『恢复』, 不需要『同步对象』和『运行标记』
交替输出 题目要求: 线程 1 输出 a 5 次,线程 2 输出 b 5 次,线程 3 输出 c 5 次。现在要求输出 abcabcabcabcabc 怎么实现
wait notify 版 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 @Slf4j(topic = "c.Test27") public class Test27 { public static void main (String[] args) { WaitNotify wn = new WaitNotify (1 , 5 ); new Thread (() -> { wn.print("a" , 1 , 2 ); }).start(); new Thread (() -> { wn.print("b" , 2 , 3 ); }).start(); new Thread (() -> { wn.print("c" , 3 , 1 ); }).start(); } } class WaitNotify { private int flag; private int loopNumber; public WaitNotify (int flag, int loopNumber) { this .flag = flag; this .loopNumber = loopNumber; } public void print (String str, int waitFlag, int nextFlag) { for (int i = 0 ; i < loopNumber; i++) { synchronized (this ) { while (flag != waitFlag) { try { this .wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print(str); flag = nextFlag; this .notifyAll(); } } } }
ReentrantLock 条件变量版 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 public class Test30 { public static void main (String[] args) throws InterruptedException { AwaitSignal awaitSignal = new AwaitSignal (5 ); Condition a = awaitSignal.newCondition(); Condition b = awaitSignal.newCondition(); Condition c = awaitSignal.newCondition(); new Thread (() -> { awaitSignal.print("a" , a, b); }).start(); new Thread (() -> { awaitSignal.print("b" , b, c); }).start(); new Thread (() -> { awaitSignal.print("c" , c, a); }).start(); Thread.sleep(1000 ); awaitSignal.lock(); try { System.out.println("开始..." ); a.signal(); } finally { awaitSignal.unlock(); } } } class AwaitSignal extends ReentrantLock { private 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(); } } } }
注意 该实现没有考虑 a,b,c 线程都就绪再开始
Park Unpark 版 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 @Slf4j(topic = "c.Test31") public class Test31 { static Thread t1; static Thread t2; static Thread t3; public static void main (String[] args) { ParkUnpark pu = new ParkUnpark (5 ); t1 = new Thread (() -> { pu.print("a" , t2); }); t2 = new Thread (() -> { pu.print("b" , t3); }); t3 = new Thread (() -> { pu.print("c" , t1); }); t1.start(); t2.start(); t3.start(); LockSupport.unpark(t1); } } class ParkUnpark { public void print (String str, Thread next) { for (int i = 0 ; i < loopNumber; i++) { LockSupport.park(); System.out.print(str); LockSupport.unpark(next); } } private int loopNumber; public ParkUnpark (int loopNumber) { this .loopNumber = loopNumber; } }
本章小结 本章我们需要重点掌握的是
分析多线程访问共享资源时,哪些代码片段属于临界区
使用 synchronized 互斥解决临界区的线程安全问题
掌握 synchronized 锁对象语法
掌握 synchronzied 加载成员方法和静态方法语法
掌握 wait/notify 同步方法
使用 lock 互斥解决临界区的线程安全问题
掌握 lock 的使用细节:可打断、锁超时、公平锁、条件变量
学会分析变量的线程安全性、掌握常见线程安全类的使用
线程安全类的方法是原子性的,但方法之间的组合要具体分析。
了解线程活跃性问题:死锁、活锁、饥饿。
应用方面
互斥:使用 synchronized 或 Lock 达到共享资源互斥效果
同步:使用 wait/notify 或 Lock 的条件变量来达到线程间通信效果
原理方面
monitor、synchronized 、wait/notify 原理
synchronized 进阶原理
park & unpark 原理
模式方面
同步模式之保护性暂停
异步模式之生产者消费者
同步模式之顺序控制