Created
June 16, 2017 16:20
-
-
Save Normal/f8ad50268faaba9d6f38b214d7c7390b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.demo; | |
import java.util.concurrent.Semaphore; | |
public class SemaphoreExample { | |
private static final Semaphore PARKING = new Semaphore(3); | |
public static void main(String[] args) throws InterruptedException { | |
for (int i = 1; i <= 9; i++) { | |
new Car(i).start(); | |
Thread.sleep(i * 100L); | |
} | |
} | |
static class Car extends Thread { | |
private int number; | |
Car(int number) { | |
this.number = number; | |
} | |
@Override | |
public void run() { | |
try { | |
System.out.println(number + " car is arrived"); | |
Thread.sleep(1000L); | |
PARKING.acquire(); | |
System.out.println(number + " car is parked"); | |
Thread.sleep(3000L); | |
PARKING.release(); | |
System.out.println(number + " car is left"); | |
} catch (InterruptedException ignored) { | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment