JUC-Semaphore

2022-3-13 diaba 多线程

package com.jiucaiyuan.net.juc.lock;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号灯(许可数量)
 * 6辆车,3个车位
 * @Author jiucaiyuan  2022/3/13 22:57
 * @mail services@jiucaiyuan.net
 */

public class SemaphoreDemo {

    public static void main(String[] args) {
        //创建许可数量
        Semaphore semaphore = new Semaphore(3);
        for(int i=1;i<=6;i++){
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"停进车位");
                    //随机停车时间
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                    System.out.println(Thread.currentThread().getName()+"离开了车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }

            },String.valueOf(i)).start();
        }
    }
}

发表评论:

Powered by emlog 京ICP备15045175号-1 Copyright © 2022