Implementing semaphore using java

I suspect that the significant difference between a mutex and a semaphore is that the semaphore count supports a maximum access of more than one, since mutext only supports one access at a time.

But with the following implementation:

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++;  
 }
}

the problem is calling the non-static wait () method of the object. But I have to apply synchronization to the class instead of instances of objects, since access to them is used by several instances.

How to resolve wait () error? Do we have another method in java or do we need to implement wait () ourselves?

+3
source share
2 answers

( , Mutex).

J2SE 5.0, util.concurrent, backported/ Java- J2SE 5.0 ( ).

Semaphore , . FIFOSemaphore.

, " Java" , , util.concurrent JSR, java.util.concurrent.

+1

, ( concurrency), / : , ( ), . :

public class MySemaphore {
   // ...
   private final Object lock = new Object();

   public static void acquire(int count) {
       while( ...) {
          synchronized(lock) {
              lock.wait();
          }
       }
   }
   public static void release(int count) {
       while( ...) {
          synchronized(lock) {
              lock.notifyAll();
          }
       }
   }
}
0

Source: https://habr.com/ru/post/1729987/


All Articles