Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- import java.util.concurrent.Semaphore;
- import java.util.Set;
- import java.util.HashSet;
- class Demontration {
- public static void main(String[] args) throws Exception {
- UnisexBathroom bathroom = new UnisexBathroom();
- Set<Thread> threads = new HashSet<Thread>();
- for (int i = 0; i < 20; i++) {
- final int index = i;
- Thread thread =
- new Thread(
- new Runnable() {
- @Override
- public void run() {
- try {
- bathroom.maleWantsToGo("Male_" + index);
- } catch (InterruptedException ie) {
- }
- }
- });
- thread.setName("Male_" + i);
- threads.add(thread);
- }
- for (int i = 0; i < 15; i++) {
- final int index = i;
- Thread thread =
- new Thread(
- () -> {
- try {
- bathroom.femaleWantsToGo("Female_" + index);
- } catch (InterruptedException ie) {
- }
- });
- thread.setName("Female_" + i);
- threads.add(thread);
- }
- for (Thread thread : threads) {
- thread.start();
- }
- for (Thread thread : threads) {
- thread.join();
- }
- }
- }
- class UnisexBathroom {
- private static final String FEMALE = "FEMALE";
- private static final String MALE = "MALE";
- private static final String NONE = "NONE";
- private static final Random random = new Random(System.currentTimeMillis());
- private static final int MAX_CAPACITY = 3;
- private static final int MAX_CONSECUTIVE_USERS = 3;
- private static final Semaphore employeesUsingBathroom = new Semaphore(MAX_CAPACITY);
- private String currentGender = NONE;
- private int consecutiveUsers = 0;
- private void useBathRoom(String name) throws InterruptedException {
- System.out.println(name + " is using the bathroom");
- Thread.sleep(random.nextInt(100));
- System.out.println(name + " is done using the bathroom");
- }
- public void maleWantsToGo(String name) throws InterruptedException {
- synchronized (this) {
- while (currentGender.equals(FEMALE)
- || (currentGender.equals(MALE) && consecutiveUsers >= MAX_CONSECUTIVE_USERS)) {
- this.wait();
- }
- currentGender = MALE;
- consecutiveUsers++;
- }
- employeesUsingBathroom.acquire();
- useBathRoom(name);
- synchronized (this) {
- employeesUsingBathroom.release();
- if (employeesUsingBathroom.availablePermits() == MAX_CAPACITY) {
- currentGender = NONE;
- consecutiveUsers = 0;
- }
- this.notifyAll();
- }
- }
- public void femaleWantsToGo(String name) throws InterruptedException {
- synchronized (this) {
- while (currentGender.equals(MALE)
- || (currentGender.equals(FEMALE) && consecutiveUsers >= MAX_CONSECUTIVE_USERS)) {
- this.wait();
- }
- currentGender = FEMALE;
- consecutiveUsers++;
- }
- employeesUsingBathroom.acquire();
- useBathRoom(name);
- synchronized (this) {
- employeesUsingBathroom.release();
- if (employeesUsingBathroom.availablePermits() == MAX_CAPACITY) {
- currentGender = NONE;
- consecutiveUsers = 0;
- }
- this.notifyAll();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement