【发布时间】:2010-01-25 23:20:50
【问题描述】:
我怀疑互斥量和信号量之间的显着区别在于计数信号量支持超过一次的最大访问,因为互斥量一次最多只支持一次访问。
但是当做如下实现时;
public class countingSemaphore{
private static final int _MOSTTABLES = 3; // whatever maximum number
private static int availtable = _MOSTTABLES;
public synchronized static void Wait(){
while(availtable==0){
try{
wait();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
availtable--;
}
public synchronized static void Signal(){
while(availtable==_MOSTTABLES){
try{
wait();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
availtable++;
}
}
问题是对象的非静态wait()方法的调用。但是,我必须对类而不是对象实例应用同步,因为访问是在多个实例之间共享的。
如何解决 wait() 错误?我们在 java 中是否有另一种方法,或者我们必须自己实现 wait()?
【问题讨论】:
-
您是否知道
java.util.concurrent中已经存在Semaphore和CountdownLatch类,或者您是否正在为作业重新实现这些东西? -
最有可能的作业,除非你在一个不允许并发的东西并且必须自己实现它的受限环境中做 java...
标签: java concurrency semaphore