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 Semaphore employeesUsingBathroom = new Semaphore(MAX_CAPACITY);
- private String currentGender = NONE;
- 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)) {
- this.wait();
- }
- currentGender = MALE;
- }
- employeesUsingBathroom.acquire();
- useBathRoom(name);
- synchronized (this) {
- employeesUsingBathroom.release();
- if (employeesUsingBathroom.availablePermits() == MAX_CAPACITY) {
- currentGender = NONE;
- }
- this.notifyAll();
- }
- }
- public void femaleWantsToGo(String name) throws InterruptedException {
- synchronized (this) {
- while (currentGender.equals(MALE)) {
- this.wait();
- }
- currentGender = FEMALE;
- }
- employeesUsingBathroom.acquire();
- useBathRoom(name);
- synchronized (this) {
- employeesUsingBathroom.release();
- if (employeesUsingBathroom.availablePermits() == MAX_CAPACITY) {
- currentGender = NONE;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement