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

 

posted @ 2017-09-26 13:41  newlangwen  阅读(1846)  评论(0编辑  收藏  举报