我需要知道是否有一些框架可以为我提供这种功能。我在一种方法中有一个关键部分,并且我需要很少的其他方法等待该关键部分执行并完成。如果临界区不活跃,这些方法应该可以顺利工作。
如果仅当没有线程处于信号量方法中时才进入临界区。
如:
public class Worker {
private Critical critical = null;
private CriticalDependent dep1 = null;
private CriticalDependent dep2 = null;
public Worker() {
critical = new Critical();
dep1 = critical.registerDependent();
dep2 = critical.registerDependent();
}
public void critical() {
critical.enter();
critical.waitForClearToGo();
// protected unique code
// change resource handle etc
critical.exit();
}
public void dependent1() {
critical.checkWaitAndUnsetClearToGo(this.dep1);
// some dependent code
// use resource handle
critical.setClearToGo(this.dep1);
}
public void dependent2() {
critical.checkWaitAndUnsetClearToGo(this.dep2);
// some dependent code
// use resource handle
critical.setClearToGo(this.dep2);
}
}
我可以找到一些解决方案,但我更喜欢使用现有的框架。而且我找不到现有的。预先感谢您。
最佳答案
使用标准Java Semaphore .
关于Java 一个临界区多个信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34241284/