MST

星途 面试题库

面试题:Java多线程编程中信号量的基本使用

在Java多线程编程里,信号量`Semaphore`常用于控制同时访问特定资源的线程数量。请编写一个简单示例,假设有一个停车场能容纳3辆车,使用`Semaphore`实现车辆进入和离开停车场的模拟,需包含线程安全的处理。
30.2万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
import java.util.concurrent.Semaphore;

public class ParkingLotSimulation {
    private static final int PARKING_SLOTS = 3;
    private static final Semaphore semaphore = new Semaphore(PARKING_SLOTS);

    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            new Thread(new Car("Car " + i)).start();
        }
    }

    static class Car implements Runnable {
        private final String name;

        public Car(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();
                System.out.println(name + " 进入停车场");
                Thread.sleep((int) (Math.random() * 2000)); // 模拟停车一段时间
                System.out.println(name + " 离开停车场");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        }
    }
}
  1. 代码说明
    • 首先定义了一个PARKING_SLOTS常量表示停车场的车位数量为3。
    • 创建了一个Semaphore对象semaphore,初始许可数量为PARKING_SLOTS
    • main方法中,启动了5个线程模拟5辆车。
    • Car类实现了Runnable接口,在run方法中,首先通过semaphore.acquire()获取许可,如果没有许可则线程阻塞,直到有许可可用。获取许可后车辆进入停车场,模拟停车一段时间后,通过semaphore.release()释放许可,确保其他车辆有机会进入停车场。finally块保证了无论线程执行过程中是否发生异常,许可都会被释放,从而保证了线程安全。