gpt4 book ai didi

java - 锁可以自动关闭吗?

转载 作者:IT老高 更新时间:2023-10-28 20:49:26 27 4
gpt4 key购买 nike

可以自动关闭吗?也就是说,而不是:

Lock someLock = new ReentrantLock();
someLock.lock();
try
{
// ...
}
finally
{
someLock.unlock();
}

...我可以说:

try (Lock someLock = new ReentrantLock())
{
someLock.lock();
// ...
}

...在 Java 7 中?

最佳答案

我自己正在考虑这样做并做了这样的事情:

public class CloseableReentrantLock extends ReentrantLock implements AutoCloseable { 
public CloseableReentrantLock open() {
this.lock();
return this;
}

@Override
public void close() {
this.unlock();
}
}

然后这是类的用法:

public class MyClass {
private final CloseableReentrantLock lock = new CloseableReentrantLock();

public void myMethod() {
try(CloseableReentrantLock closeableLock = lock.open()) {
// locked stuff
}
}
}

关于java - 锁可以自动关闭吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6965731/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com