http://wangxinchun.iteye.com/blog/1801057
synchronized 获取的锁,在方法抛出异常的时候会自动解锁
- 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;
- }
- @Override
- public 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");
- }
- }
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; } @Override public 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即可