异常与锁的释放(lock)

获取lock锁后发生异常后,线程退出,lock锁不释放


package com.horizon.thread.basic;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 演示功能:
* 当lock锁获得后如果发生异常,线程结束,但是 lock锁不会释放
* @author <a href="wangxinchun@yahoo.com.cn">新春.王</a>
*
*/
public class ThreadException extends Thread{
static Lock lock1 = new ReentrantLock();
static Lock lock2 = new ReentrantLock();
private static boolean flag = true;
public ThreadException() {

}

public static void main(String[] args) {
new ThreadException().start();
new ThreadException().start();
}

@Override
public void run() {
if(flag){
flag = false;
lock1.lock();
if(true){ //此处故意抛出运行时异常,当前线程结束,但是锁没有释放
throw new NumberFormatException();
}
lock2.lock();
System.out.println("flag :true");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock2.unlock();
lock1.unlock();
}else{
flag = true;
lock2.lock();
//再次获取lock1时 suspend
lock1.lock();
System.out.println("flag :false");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock1.unlock();
lock2.unlock();
}
super.run();
}
}

[b][color=red]注意:不是每次运行都能看的效果,请思考下,如何看到我们想要的效果效果(请逐步调试)[/color][/b]

    原文作者:java锁
    原文地址: https://blog.csdn.net/iteye_5504/article/details/82477977
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞