问题描述
有没有一个Mutex对象在java或者一种方式来创建一个?
我问,因为用1 permit初始化的Semaphore对象不能帮助我。
考虑这种情况:
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();
}
如果在第一次获取时发生异常,增加许可证,信号量不再是二进制信号量。
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?
推荐答案
查看此页面:
它有一个稍微不同的模式, (我认为)你正在寻找:
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) {
// ...
}
在这种用法中,只有在获取() release()
$ c>
In this usage, you're only calling release()
after a successful acquire()
这篇关于Java中有Mutex吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!