Java中有互斥锁吗? [英] Is there a Mutex in Java?
问题描述
java 中是否有互斥对象或创建一个对象的方法?我问是因为用 1 个许可初始化的信号量对象对我没有帮助.想想这个案例:
Is there a Mutex object in java or a way to create one? I am asking because a Semaphore object initialized with 1 permit does not help me. Think of this case:
try {
semaphore.acquire();
//do stuff
semaphore.release();
} catch (Exception e) {
semaphore.release();
}
如果第一次acquire发生异常,catch块中的释放会增加许可,信号量就不再是二元信号量了.
if an exception happens at the first acquire, the release in the catch block will increase the permits, and the semaphore is no longer a binary semaphore.
正确的方法是?
try {
semaphore.acquire();
//do stuff
} catch (Exception e) {
//exception stuff
} finally {
semaphore.release();
}
上面的代码会确保信号量是二进制的吗?
Will the above code ensure that the semaphore will be binary?
推荐答案
查看此页面:http://www.oracle.com/technetwork/articles/javase/index-140767.html
它的模式略有不同,这就是(我认为)您正在寻找的:
It has a slightly different pattern which is (I think) what you are looking for:
try {
mutex.acquire();
try {
// do something
} finally {
mutex.release();
}
} catch(InterruptedException ie) {
// ...
}
在这种用法中,您只在成功acquire()
In this usage, you're only calling release()
after a successful acquire()
这篇关于Java中有互斥锁吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!