Java多线程 synchronized 抛出异常锁自动解除
Posted newlangwen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java多线程 synchronized 抛出异常锁自动解除相关的知识,希望对你有一定的参考价值。
当一个线程执行的代码出现异常时,其所持有的锁会自动释放
public class MyObject { private int i = 1; synchronized public void methodA() throws InterruptedException { System.out.println("begin methodA threadName=" + Thread.currentThread().getName()); if(i==1){ throw new InterruptedException(); } System.out.println("end methodA "); } synchronized public void methodB() throws InterruptedException { System.out.println("begin methodB threadName=" + Thread.currentThread().getName()); System.out.println(" end methodB"); } }
ThreadA 和 ThreadB
public class ThreadA extends Thread { private MyObject myObject; public ThreadA(MyObject myObject){ this.myObject =myObject; } public void run(){ try { myObject.methodA(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public class ThreadB extends Thread { private MyObject myObject; public ThreadB(MyObject myObject){ this.myObject =myObject; } public void run(){ try { myObject.methodB(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Run
public class Run { public static void main(String[] args) { MyObject object = new MyObject(); ThreadA threadA = new ThreadA(object); threadA.setName("A"); threadA.start(); ThreadB threadB = new ThreadB(object); threadB.setName("B"); threadB.start(); } }
以上是关于Java多线程 synchronized 抛出异常锁自动解除的主要内容,如果未能解决你的问题,请参考以下文章
多线程三:Thread API,ThreadLocal,synchronized,volatile和Condition
多线程之同步synchronized的使用不当造成java.lang.IllegalMonitorStateException 异常