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();
        }
    }
}
View Code

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();    
    }
}
View Code

 

以上是关于Java多线程 synchronized 抛出异常锁自动解除的主要内容,如果未能解决你的问题,请参考以下文章

java多线程快速入门(十八)

synchronized重入后抛出异常,锁释放了吗

多线程之synchronized实现原理

多线程三:Thread API,ThreadLocal,synchronized,volatile和Condition

多线程之同步synchronized的使用不当造成java.lang.IllegalMonitorStateException 异常

C++ 多线程中的一个抛出异常