线程信号量semaphore

版权声明:Please make the source marked https://blog.csdn.net/qq_31807385/article/details/83998935

需求说明:6辆车抢占三个停车位

package hello_java;

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

public class Tool03 {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 6; i++) {
            new Thread(() -> {
//                抢占资源
                try {
                    semaphore.acquire();
                    System.out.println("车辆" + Thread.currentThread().getName() + "获得停车位");
//                停车时间
                    Thread.sleep(new Random().nextInt(1000));
//                 释放资源
                    System.out.println("车辆" + Thread.currentThread().getName() + "离开了");
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i + 1)).start();
        }
    }
}

结果如下:

车辆1获得停车位
车辆3获得停车位
车辆2获得停车位
车辆1离开了
车辆5获得停车位
车辆2离开了
车辆4获得停车位
车辆5离开了
车辆6获得停车位
车辆4离开了
车辆3离开了
车辆6离开了

猜你喜欢

转载自blog.csdn.net/qq_31807385/article/details/83998935