java7开始io就有try-with-resource。
可以利用这一个特性,来说实现,自动释放。
代码如下:
public class AutoUnlockProxy implements Closeable {
private Lock lock;
public AutoUnlockProxy(Lock lock) {
this.lock = lock;
}
@Override
public void close() throws IOException {
lock.unlock();
System.out.println("释放锁");
}
public void lock() {
lock.lock();
}
public void tryLock(long time, TimeUnit unit) throws InterruptedException {
lock.tryLock(time, unit);
}
public static void main(String[] args) {
try (AutoUnlockProxy autoUnlockProxy = new AutoUnlockProxy(new ReentrantLock())) {
autoUnlockProxy.lock();
System.out.println("加锁了");
} catch (IOException e) {
e.printStackTrace();
}
}
}
展开