LeetCode(多线程)- 1279. 红绿灯路口

题目链接:点击打开链接

题目大意:略。

解题思路:略。

相关企业

  • 亚马逊(Amazon)
  • 高盛集团(Goldman Sachs)
  • 苹果(Apple)
  • 微软(Microsoft)
  • 谷歌(Google)
  • 彭博(Bloomberg)
  • 阿里巴巴
  • 字节跳动

AC 代码

class TrafficLight {
    private Semaphore greenLight; // 红绿灯遥控器
    private boolean road1CanGo; // 表示道路1是绿灯
    private boolean road2CanGo; // 表示道路2是绿灯

    public TrafficLight() {
        this.greenLight = new Semaphore(1, true);
        this.road1CanGo = true;
        this.road2CanGo = false;
    }

    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
    ) {
        try {
            // 申请获取遥控器
            greenLight.acquire(); 
            // 如果当前车道已经是绿灯了,直接通过
            if ((roadId == 1 && road1CanGo) || (roadId == 2 && road2CanGo)) crossCar.run();
            else if (roadId == 1 && !road1CanGo) { // 否则,如果道路1不是绿灯,用遥控器变成绿灯
                turnGreen.run();
                road1CanGo = true;
                road2CanGo = false;
                crossCar.run();
            } else if (roadId == 2 && !road2CanGo) { // 如果道路2不是绿灯,用遥控器变成绿灯
                turnGreen.run();
                road2CanGo = true;
                road1CanGo = false;
                crossCar.run();
            }
            // 最后把遥控器归还
            greenLight.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陆克和他的那些代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值