8
I have to solve this problem using Java semaphores, but I have no idea how, and I cannot find any related Java materials. This is how it goes:
There are to kinds of threads: men and women. Both wants to use same resources which quantity is BATHROOM_SIZE. 5 rules:
- Every thread, after signaling need of using resource, should wait until he will be able to use it.
- Prevent situation, when more than BATHOOM_SIZE threads is using resource concurrently.
- Prevent woman and man use bathoom in the same time.
- Threads should use resources concurrently. If there are many threads of one type, up to BATHROOM_SIZE threads should use resource.
- Prevent starvation.
Results
Works for:
1woman, 1man, 5women, 5men
Fails for:
5women1men, 5men1women, 2men2women, 5men5women.
I've been trying to make it work since Monday and now I've run out of ideas.
Code
So my task is to write Bathroom.java class which implements BathroomInterface:
public interface BathroomInterface {
public static final int BATHROOM_SIZE = 3; //3 is just example
void manEnter();
void manExit();
void womanEnter();
void womanExit();
}
In system there are a number of man and woman threads which work like this:
for(int i = 0; i < n; i++) {
bathroom.manEnter();
//uses bathroom random amount of time
bathroom.manExit();
}
for(int i = 0; i < m; i++) {
bathroom.womanEnter();
//uses bathroom random amount of time
bathroom.womanExit();
}
I also have scheme of Bathroom.java class, I have to extend:
import java.util.concurrent.Semaphore;
public class Bathroom implements BathroomInterface {
private Semaphore mutex = new Semaphore(1, true);
public void womanEnter() {
mutex.acquireUninterruptibly();
}
public void womanExit() {