Answer the question
In order to leave comments, you need to log in
Can a simaphore in Java give no permissions at all?
Here's a problem for the "producer-consumer". I don't understand how semCon can allow entry if it has 0 permissions?
import java.util.concurrent.Semaphore;
/**
* Created by Dell on 16.09.2014.
*/
public class Exchanger {
volatile int someRandomValue;
volatile boolean isFilled = false;
Semaphore semProd = new Semaphore(1);
Semaphore semCon = new Semaphore(0);
void put(int n){
try {
semProd.acquire();
}
catch (InterruptedException e){
e.printStackTrace();
}
someRandomValue = n;
System.out.println("Сгенерировано значение " + someRandomValue);
semCon.release();
}
int read(){
try{
semCon.acquire();
}
catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("Считано занчение " + someRandomValue);
semProd.release();
return someRandomValue;
}
}
Answer the question
In order to leave comments, you need to log in
Did you call put(n) first and then read()?
You have a typo:
semCon.release(); - should be semProd.release();
and semProd.release(); - should be semCon.release();
Those. at the end of the put method, you resolve one acquire to the semCon semaphore and then in the read() method you acquire into it, if you call read() and put(n) in reverse order, then you will hang in the try block of the read method.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question