Leetcode_1279_红绿灯路口_多线程

本文介绍了一种使用布尔变量和信号量实现交通灯控制的方法。通过一个`TrafficLight`类,可以确保不同道路上的车辆在交叉口正确通行。当车辆到达时,程序会检查当前灯的状态并决定是否改变灯的颜色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用一个布尔型变量保存目前红绿灯状态。
如果目前的车能通过红绿灯,就让他通过。
如果不能,改变灯的状态。

class TrafficLight {
    boolean isAGreen;    

    public TrafficLight() {
        isAGreen = true;
    }
    
    synchronized public void carArrived(
        int carId,           // ID of the car
        int roadId,          // ID of the road the car travels on. Can be 1 (road A) or 2 (road B)
        int direction,       // Direction of the car
        Runnable turnGreen,  // Use turnGreen.run() to turn light to green on current road
        Runnable crossCar    // Use crossCar.run() to make car cross the intersection 
    ) {
        if(roadId == 2 && isAGreen==true ||roadId == 1 && isAGreen == false)
        {
            turnGreen.run();
            isAGreen = !isAGreen;
        }
        crossCar.run();
    }
}

当然也可以用信号量的方法,相对速度肯定慢。

class TrafficLight {
    private Semaphore s;
    boolean isAGreen;
    public TrafficLight() {
        s = new Semaphore(1);
        isAGreen = true;
    }
    public void carArrived(
            int carId,           // ID of the car
            int roadId,          // ID of the road the car travels on. Can be 1 (road A) or 2 (road B)
            int direction,       // Direction of the car
            Runnable turnGreen,  // Use turnGreen.run() to turn light to green on current road
            Runnable crossCar    // Use crossCar.run() to make car cross the intersection 
    ) throws InterruptedException {
        s.acquire();
        if(roadId == 2 && isAGreen==true ||roadId == 1 && isAGreen == false)
        {
            turnGreen.run();
            isAGreen = !isAGreen;
        }
        crossCar.run();
        s.release();
    }
}
### 使用 synchronized 解决 LeetCode 红绿灯路口问题 红绿灯路口问题是典型的多线程同步问题之一,其目标是确保两条道路的车辆交替通过交叉口而不会发生冲突。此问题可以通过 Java 中的 `synchronized` 关键字实现互斥访问资源的功能来完成。 #### 1. **核心需求** 根据题目描述,需要满足以下条件: - 同一时间只允许一条道路上的车辆通过。 - 当前道路上的车辆全部通过后,切换到另一条道路。 - 防止死锁或饥饿现象的发生。 这些需求可以通过使用对象级别的锁 (`synchronized`) 来实现[^1]。 #### 2. **Java 实现方案** 下面是基于 `synchronized` 的完整实现: ```java class TrafficLight { private boolean roadAIsGreen; public TrafficLight() { this.roadAIsGreen = true; // 初始化时,默认 Road A 是绿灯 } public synchronized void carArrived( int carId, // ID of the car arriving at the intersection int roadId, // ID of the road the car travels on (1 for Road A, 2 for Road B) int direction, // Direction that the car will take after crossing the intersection Runnable turnGreen, // Function to call to turn light to green for current road Runnable crossCar // Function to call to let car cross the intersection ) { // 如果当前路不为绿灯,则切换绿灯 if ((roadId == 1 && !roadAIsGreen) || (roadId == 2 && roadAIsGreen)) { turnGreen.run(); // 切换绿灯 roadAIsGreen = !roadAIsGreen; // 更新状态 } crossCar.run(); // 让汽车通过十字路口 } } ``` 在这段代码中,`TrafficLight` 类维护了一个布尔变量 `roadAIsGreen` ,用于跟踪哪条道路目前拥有绿灯。每次调用 `carArrived()` 方法时,会检查当前道路的状态是否匹配。如果不匹配,则调用 `turnGreen.run()` 进行切换,并更新内部状态。最后,无论哪种情况都让车辆通过交叉口。 由于整个方法被声明为 `synchronized`,因此同一时刻只会有一个线程能够进入该方法体,从而实现了对共享资源的安全访问。 #### 3. **运行原理说明** - 每次有车到达时,先判断当前道路是否为绿灯。 - 如果不是,则调用回调函数 `turnGreen.run()` 改变信号灯颜色。 - 接着调用 `crossCar.run()` 允许车辆通过。 - 所有的操作都在同一个同步块内完成,保证了数据的一致性和安全性。 这种方法利用了 Java 提供的基础同步机制——`synchronized`,有效地防止了多个线程同时修改共享资源而导致的数据竞争问题。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值