特点:给定一个数值,然后得到,释放,循环往复。可以用到限流的场景。

    1. import java.util.concurrent.Semaphore;
    2. import java.util.concurrent.TimeUnit;
    3. public class SemaphoreDemo {
    4. public static void main(String[] args) {
    5. // 线程数量:停车位! 限流!
    6. Semaphore semaphore = new Semaphore(3);
    7. for (int i = 1; i <=6 ; i++) {
    8. new Thread(()->{
    9. // acquire() 得到
    10. try {
    11. semaphore.acquire();
    12. System.out.println(Thread.currentThread().getName()+"抢到车位");
    13. TimeUnit.SECONDS.sleep(2);
    14. System.out.println(Thread.currentThread().getName()+"离开车位");
    15. } catch (InterruptedException e) {
    16. e.printStackTrace();
    17. } finally {
    18. semaphore.release(); // release() 释放
    19. }
    20. },String.valueOf(i)).start();
    21. }
    22. }
    23. }