在Java中重新填充BlockedQueue

时间:2013-12-25 09:55:27

标签: java multithreading concurrency queue fill

所以我有这个循环

public void run()
{
    while(true)
    {
        //Look at everything on queue currently and pulls them into a list
        List<ElevatorCall> callsWaiting = new ArrayList<ElevatorCall>();
        queue.drainTo(callsWaiting);

        ElevatorCall nextDestination = getBestOption(callsWaiting);


        System.out.println("Picked Person(" + nextDestination.getPerson().getId() + ") as best option");

        //Work on this section
        if(nextDestination != null)
        {
            sortCallsByShortestDistanceAndDirection(workQueue, nextDestination.getDirection());

            boolean arrived = moveTowards(nextDestination);

            while(!arrived)
            {
                //Check for new calls
                List<ElevatorCall> newCalls = new ArrayList<ElevatorCall>();
                queue.drainTo(newCalls);

                checkFloorForCallsAndAddToElevator(workQueue);
                sortCallsByShortestDistanceAndDirection(newCalls, nextDestination.getDirection());

                arrived = moveTowards(nextDestination);
            }
            arrived = false;
        }
    }
}

我希望它继续四处寻找目的地楼层。但是,当它找到第一个目标层时,循环结束,因为当它返回到顶层时,queue.drainTo(callsWaiting)不起作用,因为队列已经被清空。我认为我设置到假之后需要重新填充它,但是我不知道该怎么做。 感谢您对此的任何帮助。

1 个答案:

答案 0 :(得分:0)

我不确定你的getBestoption是做什么的。如果您在队列中有3个请求(7楼,8楼,20楼),那么在进行循环之前。

while(true)
{
    //Look at everything on queue currently and pulls them into a list
    List<ElevatorCall> callsWaiting = new ArrayList<ElevatorCall>();
    queue.drainTo(callsWaiting);

    ElevatorCall nextDestination = getBestOption(callsWaiting);


在上面的部分中,您正在检索所有请求并将其置于等待呼叫中(3个ElevatorCall对象在呼叫等待中。当您获得nextDestination时(我假设您在7楼当前的电梯被选中,并取消第7层)来自呼叫等待的楼层请求,然后通过剩余线路处理7楼请求。但是当你/如何处理呼叫等待中的其他两个请求时? 而不是条件

 //Work on this section
    if(nextDestination != null)

左边有循环,会解决你的问题。像

while (nextDestination != null) {
       sortCallsByShortestDistanceAndDirection(workQueue, nextDestination.getDirection());

        boolean arrived = moveTowards(nextDestination);

        while(!arrived)
        {
            //Check for new calls
            List<ElevatorCall> newCalls = new ArrayList<ElevatorCall>();
            queue.drainTo(newCalls);

            checkFloorForCallsAndAddToElevator(workQueue);
            sortCallsByShortestDistanceAndDirection(newCalls, nextDestination.getDirection());

            arrived = moveTowards(nextDestination);
        }
        arrived = false;
        nextDestination = getBestOption(callsWaiting);    

}

注意**,从getBestoption中选择nextDestination,如果传递的集合为空,则假定getBestoption返回null。