线程抛出异常后,synchronized锁会不会主动释放 —笔记
思路: 创建两个线程分别访问同一对象的不同方法,在第一个方法主动抛出异常,如果第二个方法正常执行,则会主动释放,反之亦然。
代码:
public class SynchronizedTest implements Runnable{
static SynchronizedTest instance = new SynchronizedTest();
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(instance);
Thread thread2 = new Thread(instance);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("finished");
}
@Override
public void run() {
if (Thread.currentThread().getName().equals("Thread-0")) {
method1();
} else {
method2();
}
}
public synchronized void method1(){
System.out.println("我叫"+Thread.currentThread().getName());
try {
Thread.sleep(3000);
} catch(InterruptedException e) {
e.printStackTrace();
}
throw new RuntimeException();
//System.out.println(Thread.currentThread().getName()+"运行完毕");
}
public synchronized void method2(){
System.out.println("我叫"+Thread.currentThread().getName());
try {
Thread.sleep(3000);
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"运行完毕");
}
}
运行结果:
我叫Thread-0
我叫Thread-1
Exception in thread "Thread-0" java.lang.RuntimeException
at wl.test.SynchronizedTest.method1(SynchronizedTest.java:33)
at wl.test.SynchronizedTest.run(SynchronizedTest.java:20)
at java.lang.Thread.run(Thread.java:745)
Thread-1运行完毕
finished
说明抛出异常后会释放锁0.0