標籤:釋放 exception ted interrupt generate zed view xtend alt
當一個線程執行的代碼出現異常時,其所持有的鎖會自動釋放
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 拋出異常鎖自動解除