重入锁在java中自动释放

时间:2014-06-06 10:43:05

标签: java interface locking

我们有什么方法可以自动释放重入锁。如果没有解锁,最终阻止是否有任何方法可以实现此目的

try{
lock.lock;

}
catch(Exception e){

lock.unlock

}

1 个答案:

答案 0 :(得分:0)

可以使用注释完成,但使用AutoCloseable也是一个选项:

import java.util.concurrent.locks.ReentrantLock;

public class LockTry {

public static void main(String[] args) {

    new LockTry().testWithLock();
}

private void testWithLock() {

    ReentrantLock lock = new ReentrantLock();
    try (CloseableLock clock = new CloseableLock(lock)) {
        System.out.println("run with lock");
    }
}

static class CloseableLock implements AutoCloseable {

    private final ReentrantLock lock;

    CloseableLock(ReentrantLock lock) {
        super();
        this.lock = lock;
        lock.lock();
        System.out.println("locked");
    }

    @Override
    public void close() {
        lock.unlock();
        System.out.println("unlocked");
    }
}
}