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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值