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().
package operating_system;
import java.util.ArrayList ;
public class Semaphore {
private int value ;
private ArrayList <SemProc> queue ;
public Semaphore(int i) {
value = i ;
queue = new ArrayList <SemProc> () ;
}
public synchronized void V() { //release
value++;
if ( value >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 >= 0 )
return;
else { // no available resources
t.removeFromReadyQueue();
queue.add(t);
try {
wait();
} catch (InterruptedException e) {e.printStackTrace();}
}}}}