所以我试图弄清楚电梯在单个实例中如何工作。它获取人员的到达楼层及其目的地,并成功移动到到达楼层。但是我不太确定如何使其正常工作。 它的目的是等待另一个人被添加到调用队列中,但它无法正常工作。
这是电梯类中的 run() 方法
@Override
public synchronized void run()
{
while(true)
{
List<ElevatorCall> callsWaiting = new ArrayList<ElevatorCall>();
queue.drainTo(callsWaiting);
for(int i = 0; i < callsWaiting.size(); i++)
{
boolean directionToGo = getDirection(callsWaiting.get(i).getDestinationFloor(), currentPosition);
int floorsToGoForCollection = getFloorsToGo(callsWaiting.get(i).getCollectionFloor());
int floorsToGoForDestination = getFloorsToGo(callsWaiting.get(i).getDestinationFloor());
//System.out.println("Elevator is moving to floor #" + callsWaiting.get(i).getCollectionFloor());
System.out.println("Elevator is on floor " + currentPosition);
for(int j = 0; j < floorsToGoForCollection + 1; j++)
{
boolean wasPersonOnFloor = checkIfPersonIsOnFloor(currentPosition, callsWaiting);
boolean isDestinationFloor = checkIfDestination(currentPosition, currentElevatorCalls);
if(wasPersonOnFloor)
{
currentElevatorCalls.add(callsWaiting.get(floorsToGoForCollection - j));
System.out.println("A person on this floor called the elevator");
//floorsToGoForCollection = getFloorsToGo(callsWaiting.get(i).getDestinationFloor());
//j = 0;
directionToGo = getDirection(callsWaiting.get(i).getDestinationFloor(), currentPosition);
break;
}
if(isDestinationFloor)
callsWaiting = removeDestinationFromQueue(currentPosition, callsWaiting);
if(callsWaiting.size() == 0)
{
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//floorsToGoForCollection = getFloorsToGo(callsWaiting.get(i).getCollectionFloor());
//floorsToGoForDestination = getFloorsToGo(callsWaiting.get(i).getDestinationFloor());
wasPersonOnFloor = false;
moveFloor(directionToGo);
}
}
}
}
在我的主类中,我有这段代码来模拟它。 我相当确定 run() 中的逻辑不正确,但我似乎无法弄清楚它的哪个方面。
run();
Elevator elevator = new Elevator(queue);
elevator.run();
}
public synchronized static void run()
{
Random rand = new Random();
int waitTime = rand.nextInt((1000 - 100) + 1) + 100;
int startingID = 1;
List<Person> people = new ArrayList<Person>(startingID);
people.add(new Person(queue));
for(int i = 0; i < people.size(); i++)
{
people.get(i).run();
}
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
感谢您对逻辑的任何帮助。
最佳答案
您的Elevator
类或Person
是否扩展了Thread
?请记住,要启动线程
,您必须调用start()
,而不是run()
。如果它是 Runnable
,则必须将其传递给新的 Thread
对象并 start()
该新线程。也许您的代码没有前进,因为它被困在循环中,因为它是在单个线程中处理的?
关于java - 电梯寻找楼层模拟中的逻辑存在缺陷,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20763172/