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

《Java多线程(八) synchronized 抛出异常锁自动解除》
《Java多线程(八) synchronized 抛出异常锁自动解除》

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

《Java多线程(八) synchronized 抛出异常锁自动解除》
《Java多线程(八) synchronized 抛出异常锁自动解除》

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

 

    原文作者:newlangwen
    原文地址: http://www.cnblogs.com/newlangwen/p/7596353.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞