synchronized 和异常的关系,如果没有对异常进行try,则会释放锁,结束线程执行
测试代码如下
/** * synchronized 和异常的关系 * T2线程能否执行? */ @Slf4j(topic = "test") public class Demo { Object o = new Object(); int count = 0; void test(){ synchronized(o) { //t1进入并且启动 log.debug(Thread.currentThread().getName() + " start......"); //t1 会死循环 t1 讲道理不会释放锁 while (true) { count++; log.debug(Thread.currentThread().getName() + " count = " + count); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } //加5次之后 发生异常 /** * 如果程序发生异常如果没有try 则会释放锁 * 反之不会释放锁 */ if (count == 5) { int i = 1 / 0; } } } } public static void main(String[] args) { Demo demo11 = new Demo(); // Runnable r = () -> demo11.test(); // new Thread(r, "t1").start(); new Thread(()->{ demo11.test(); },"t1").start(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(()->{ demo11.test(); }, "t2").start(); } }
打印结果
17:23:39.128 [t1] DEBUG test - t1 start......
17:23:39.132 [t1] DEBUG test - t1 count = 1
17:23:40.132 [t1] DEBUG test - t1 count = 2
17:23:41.133 [t1] DEBUG test - t1 count = 3
17:23:42.133 [t1] DEBUG test - t1 count = 4
17:23:43.134 [t1] DEBUG test - t1 count = 5
Exception in thread "t1" 17:23:44.135 [t2] DEBUG test - t2 start......
17:23:44.135 [t2] DEBUG test - t2 count = 6
java.lang.ArithmeticException: / by zero
at com.fala.base.test.demo8.Demo.test(Demo.java:36)
at com.fala.base.test.demo8.Demo.lambda$main$0(Demo.java:48)
at java.lang.Thread.run(Thread.java:745)
17:23:45.135 [t2] DEBUG test - t2 count = 7
17:23:46.136 [t2] DEBUG test - t2 count = 8
17:23:47.137 [t2] DEBUG test - t2 count = 9
17:23:48.137 [t2] DEBUG test - t2 count = 10
17:23:49.138 [t2] DEBUG test - t2 count = 11
17:23:50.139 [t2] DEBUG test - t2 count = 12
17:23:51.139 [t2] DEBUG test - t2 count = 13
17:23:52.139 [t2] DEBUG test - t2 count = 14
17:23:53.140 [t2] DEBUG test - t2 count = 15