title: how to ensure thread-safe when using the semaphore
body: <p>I want to add a synchronised section of code after first acquire the semaphore and I am not allowed to synchronised the function. So I wrote the following codes. Unfortunately, from the output, my program was blocked. Why is that? And how should I change the code if I could only change the context inside the P() and V().</p>
  
  <pre><code>package operating_system;
  
  import java.util.ArrayList ;
  
  public class Semaphore {
  
     private int value ;
     private ArrayList &lt;SemProc&gt; queue ;
  
     public Semaphore(int i) {
        value = i ;
        queue = new ArrayList &lt;SemProc&gt; () ;
     }
  
     public synchronized void V() {  //release
         value++;
         if ( value &gt;0 )
             return;
         else {//someone else is waiting
             if ( !queue.isEmpty() ){
             SemProc Runner = queue.get(0);
             queue.remove(0);
             Runner.addToReadyQueue(true);
             }
         }
     }
  
     public void P(SemProc t) { //acquire
         synchronized (this){
         value--;
         if ( value &gt;= 0 ) 
             return;
         else { // no available resources
             t.removeFromReadyQueue();
             queue.add(t);
             try {
              wait();
          } catch (InterruptedException e) {e.printStackTrace();}
     }}}}
  </code></pre>