深入理解JUC:第六章:Semaphore信号灯

理论:

Semaphore 是 synchronized 的加强版,作用是控制线程的并发数量

多个线程抢多个资源,下面案例是有六台车抢三个停车位

使用Semaphore的代码:

public class Demo {

    public static void main(String[] args) throws Exception{
        //模拟三个停车位
        Semaphore semaphore = new Semaphore(3);
        //模拟六台车
        for (int i = 1; i <= 6; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();//减一
                    //semaphore.release();//加一
                    //semaphore.release(2);//加二
                    System.out.println(Thread.currentThread().getName()+"\t 抢到车位");
                    Thread.sleep(2000);
                    System.out.println(Thread.currentThread().getName()+"\t 停车2秒后离开车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }
    }
}

控制台:

发布了276 篇原创文章 · 获赞 181 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/java_wxid/article/details/99174538