异常与锁的释放(synchronized )

来源:互联网 发布:php网站开发视频教程 编辑:程序博客网 时间:2024/06/06 18:04

http://wangxinchun.iteye.com/blog/1801057

synchronized 获取的锁,在方法抛出异常的时候会自动解锁

Java代码 复制代码 收藏代码
  1. package com.horizon.thread.synchronize;   
  2.   
  3. /**  
  4.  * function:主要演示了 synchronized 获取的锁,在方法抛出异常的时候会自动解锁 
  5.  * @author <a href="wangxinchun@yahoo.com.cn">新春.王</a> 
  6.  *   
  7.  */  
  8. public class SynchronizeException extends Thread{   
  9.     private static volatile boolean flag = true;   
  10.     private A a;   
  11.     private B b;   
  12.     public static void main(String[] args) {   
  13.         A a = new A();   
  14.         B b = new B();   
  15.         new SynchronizeException(a,b).start();   
  16.         new SynchronizeException(a,b).start();   
  17.     }   
  18.        
  19.     public SynchronizeException(A a,B b) {   
  20.         this.a = a;   
  21.         this.b = b;   
  22.     }   
  23.        
  24.     @Override  
  25.     public void run() {   
  26.         if(flag){   
  27.             flag = false;   
  28.             a.a1();   
  29.             b.b1();   
  30.         }else{   
  31.             flag = true;   
  32.             b.b1();   
  33.             a.a1();   
  34.         }   
  35.     }   
  36. }   
  37.   
  38. class A {   
  39.     public synchronized void a1() {   
  40.                  // 此处可以设置断点,两个线程只有一个可以执行   
  41.         System.out.println(Thread.currentThread()+"a1");   
  42.         if(true){   
  43.             throw new NumberFormatException();   
  44.         }   
  45.     }   
  46. }   
  47.   
  48. class B {   
  49.     public synchronized void b1() {   
  50.         System.out.println(Thread.currentThread()+"b1");   
  51.     }   
  52. }  
package com.horizon.thread.synchronize;/** * function:主要演示了 synchronized 获取的锁,在方法抛出异常的时候会自动解锁 * @author <a href="wangxinchun@yahoo.com.cn">新春.王</a> *  */public class SynchronizeException extends Thread{private static volatile boolean flag = true;private A a;private B b;public static void main(String[] args) {A a = new A();B b = new B();new SynchronizeException(a,b).start();new SynchronizeException(a,b).start();}public SynchronizeException(A a,B b) {this.a = a;this.b = b;}@Overridepublic void run() {if(flag){flag = false;a.a1();b.b1();}else{flag = true;b.b1();a.a1();}}}class A {public synchronized void a1() {                 // 此处可以设置断点,两个线程只有一个可以执行System.out.println(Thread.currentThread()+"a1");if(true){throw new NumberFormatException();}}}class B {public synchronized void b1() {System.out.println(Thread.currentThread()+"b1");}}



注意:要想看到效果必须逐步调试按照特定的步骤才能保证看到效果
另外:class B 的方法是为了其他功能而设计的,请只需关注class A即可