java线程持锁状态下出现异常会释放锁

线程持锁状态下出现异常是否会释放锁?于是做了个实验:

public class LockTest {

public static class ThreadTest implements Runnable {

    private ReadWriteLock lock;
    private Lock readLock;
    private Lock writeLock;
    private int arg0;

    public void run() {
        writeLock.lock();
        try {
            String name = Thread.currentThread().getName();
            System.out.println(name + " start...");
            long now = System.currentTimeMillis();
            System.out.println(name + " start:" + now);
            //System.out.println(10 / arg0);
            try {
                Thread.sleep(5000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(10 / arg0);
            long end = System.currentTimeMillis();
            System.out.println(name + " end:" + end);
            System.out.println(name + " use time:" + (end - now));
            System.out.println(name + " end...");

        } finally {
            writeLock.unlock();
        }

    }

    public ThreadTest(ReadWriteLock lock, int arg0) {
        this.lock = lock;
        this.readLock = lock.readLock();
        this.writeLock = lock.writeLock();
        this.arg0 = arg0;
    }
}

public static void test01() {
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    ThreadTest t1 = new ThreadTest(lock, 0);
    ThreadTest t2 = new ThreadTest(lock, 1);

    Thread thread1 = new Thread(t1, "th1");
    Thread thread2 = new Thread(t2, "th2");

    thread1.start();
    thread2.start();
}

public static void main(String[] args) {
    test01();
}

}
执行结果:
th1 start…
th1 start:1495075673822
th2 start…
[WARNING]
th2 start:1495075678827
java.lang.ArithmeticException: / by zero
at basic.simple.LockTest$ThreadTest.run(LockTest.java:38)
at java.lang.Thread.run(Thread.java:745)
10
th2 end:1495075683830
th2 use time:5003
th2 end…

结论:线程持锁状态下出现异常会释放锁。

猜你喜欢

转载自blog.csdn.net/zxk364961978/article/details/72459125