【问题标题】:Execute multiple objects' methods at the same time using Executed Service使用 Executed Service 同时执行多个对象的方法
【发布时间】:2017-02-24 18:08:42
【问题描述】:

我正在尝试建立一个交通信号灯系统来控制一个路口。我有一个控制器类,它将执行路口的各个阶段,例如,第一阶段将使用 Thread.sleep 将南北和南北交通信号灯变为绿灯一段时间,然后在第二阶段相同相,但适用于东西向和东西向交通信号灯。

我的问题是我想同时打开每个阶段的所有交通灯,这样南北和南北交通灯会同时变绿和变红。我曾尝试使用 ExecutedService 框架,但它似乎无法正常工作,这是我的代码。如果您需要任何进一步的信息以便给我一个有用的答案,请不要犹豫,问

这是控制器类的启动方法,它将连续运行阶段,控制器将阶段作为对象 LinkedList 的列表。

public void start() throws Exception {

        // if there are no phases(cycles) to be executed in sequence
        if (phases.isEmpty()) {
            throw new Exception("There are no phases been created for the intersection to be controlled");
        }

        Iterator<Phase> iteratorP = phases.iterator();

        //execute phases in sequence
        while (iteratorP.hasNext()) {
            Phase phase = iteratorP.next();
            System.out.println("phase activated: ");
            // will activate the phase by turning all the traffic lights in this phase to green light
            phase.activate();

        }
    }

===================================== 这是阶段类。此类将有一个交通灯列表列表,该列表将在一定时间内变为绿色然后变为红色

protected void activate() {

        ExecutorService executorService = Executors.newFixedThreadPool(trafficLights.size());
        executorService.execute(new Runnable() {
            public void run() {
                for (TrafficLight tl : trafficLights) {

                    tl.nextState();
                    System.out.println("TrafficLight nextState done");

                    try {
                        //PrepareToStopSate = Amber Light
                        //PrepareToGoState = Amber + Red Lights

                        if (tl.getCurrentState() instanceof PrepareToStopState ||
                            tl.getCurrentState() instanceof PrepareToGoState) {
                            System.out.println("wait 2sec");

                            //will wait for two seconds then chnage the state to next state GoState or StopState
                            Thread.currentThread().sleep(pause * 1000);
                            System.out.println("TL nextState done");
                            tl.nextState();
                        } else {
                            //if the state of the traffic light is either GoState(green) or StopState(red)
                            //wait for (duration) time then change the state
                            System.out.println("wait duration for green and red");
                            Thread.currentThread().sleep(duration * 1000);
                        }
                    } catch (Exception e) {
                    }

                }
            }
        });

    }

【问题讨论】:

    标签: java multithreading traffic


    【解决方案1】:

    根据我对您代码的理解,只有一个线程会在您的 ExecutorService 的 execute 方法中运行该线程(您的代码中只执行一个 Runnable!)。

    再次,如果我的理解是正确的,你应该让每个 TrafficLight 实现 Runnable,然后有如下代码:

    protected void activate(){
    //some code
    ExecutorService executorService = Executors.newFixedThreadPool(trafficLights.size());    
    for (TrafficLight tl: trafficLights){
              executor.execute(tl);
        }
    //some other code
    }
    

    您可能还想看看CountDownLatch 类,而不是使用 Thread.sleep()。

    对于具有 Runnable 的类,这是您实现逻辑的地方,因此根据您的代码,它看起来像:

    public class TrafficLight implement Runnable{
    
    //Some methods
    @Override
    public void run(){
    
                        tl.nextState();
                        System.out.println("TrafficLight nextState done");
    
                        try {
                            //PrepareToStopSate = Amber Light
                            //PrepareToGoState = Amber + Red Lights
    
                            if (tl.getCurrentState() instanceof PrepareToStopState ||
                                tl.getCurrentState() instanceof PrepareToGoState) {
                                System.out.println("wait 2sec");
    
                                //will wait for two seconds then chnage the state to next state GoState or StopState
                                Thread.currentThread().sleep(pause * 1000);
                                System.out.println("TL nextState done");
                                tl.nextState();
                            } else {
                                //if the state of the traffic light is either GoState(green) or StopState(red)
                                //wait for (duration) time then change the state
                                System.out.println("wait duration for green and red");
                                Thread.currentThread().sleep(duration * 1000);
                            }
                        } catch (Exception e) {
                        }
    
                    }
    }
    

    【讨论】:

    • 实现Runnable接口后,run()方法的实现应该是什么?只有你给了什么?你的代码应该在哪个类?
    • 你的答案很清楚,但是是不是要在第一阶段把所有的红绿灯一起打开,而不是在接下来的阶段碰红绿灯?
    • 我看到你使用了红绿灯类来编写逻辑。那不能来自阶段或控制器吗?
    • 你问的是执行人服务,这就是我回答的目的。不幸的是,关于红绿灯的逻辑我不能说太多。我建议您尝试实现一个控制器,该控制器将处理线程以保持您的交通灯组之间的一致状态。
    • 好的我明白了,但是为了让每个红绿灯成为一个线程或独立同时工作,红绿灯必须实现Runnable接口吗?再次感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多