首页 » Java » java线程持锁状态下出现异常会释放锁

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

2017-05-18 12:21:01阅读(460)

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

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…

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

最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹