在这个Service中的Integer.paseInt(“a”)一定会发成异常,然后再测试类中使用了Thread进行了sleep,然后可以观察到结果就是线程A执行的时候已经进入到异常的代码块中。此时已经释放了锁。但是B也启动了线程,但是b不满足判断的条件,所以B进入了else。从这里看出线程遇到异常的时候就会释放锁。
package com.mayuhan.throwExceptionLock;
public class Service {
synchronized public void testMethod() {
if(Thread.currentThread().getName().equals("a")) {
System.out.println("ThreadName="+Thread.currentThread().getName()+"runTime"+System.currentTimeMillis());
int i =1;
while(i == 1) {
if((""+Math.random()).substring(0,8).equals("0.123456")) {
System.out.println("ThreadName="+Thread.currentThread().getName()+"run exception time = "+System.currentTimeMillis());
Integer.parseInt("a");
}
}
}else {
System.out.println("Thread B run time"+System.currentTimeMillis());
}
}
}
创建线程A
package com.mayuhan.throwExceptionLock;
public class ThreadA extends Thread{
private Service service;
public ThreadA( Service service) {
this.service = service;
}
@Override
public void run() {
super.run();
service.testMethod();
}
}
创建线程B
package com.mayuhan.throwExceptionLock;
public class ThreadB extends Thread{
private Service service;
public ThreadB( Service service) {
this.service = service;
}
@Override
public void run() {
super.run();
service.testMethod();
}
}
创建了测试类进行测试
package com.mayuhan.throwExceptionLock;
public class Test {
public static void main(String[] args) {
try {
Service service = new Service();
ThreadA t1 = new ThreadA(service);
t1.setName("a");
t1.start();
Thread.sleep(5000);
ThreadB t2 = new ThreadB(service);
t2.setName("b");
t2.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}