Skip to content

Instantly share code, notes, and snippets.

@Normal
Created June 16, 2017 16:20
Show Gist options
  • Save Normal/f8ad50268faaba9d6f38b214d7c7390b to your computer and use it in GitHub Desktop.
Save Normal/f8ad50268faaba9d6f38b214d7c7390b to your computer and use it in GitHub Desktop.
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