电梯调度算法python
时间: 2023-11-25 07:52:22 浏览: 150
算法电梯调度
电梯调度算法是指在多个电梯之间合理地分配任务,使得电梯的运行效率最高,乘客等待时间最短。下面是一个简单的Python电梯调度算法的实现:
```python
import threading
import time
import queue
class Elevator(threading.Thread):
def __init__(self, name, max_floor, task_queue):
super().__init__(name=name)
self.max_floor = max_floor
self.current_floor = 1
self.direction = 1
self.task_queue = task_queue
self.task_queue.put((self.current_floor, self.direction))
def run(self):
while True:
if not self.task_queue.empty():
task = self.task_queue.get()
target_floor, direction = task
self.direction = direction
while self.current_floor != target_floor:
self.current_floor += self.direction
print(f"{self.name} is at floor {self.current_floor}")
time.sleep(1)
print(f"{self.name} is opening the door")
time.sleep(1)
print(f"{self.name} is closing the door")
time.sleep(1)
else:
time.sleep(1)
if __name__ == '__main__':
task_queue = queue.Queue()
elevator1 = Elevator("Elevator 1", 16, task_queue)
elevator2 = Elevator("Elevator 2", 16, task_queue)
elevator1.start()
elevator2.start()
while True:
target_floor = int(input("Please input the target floor: "))
direction = int(input("Please input the direction (1 for up, -1 for down): "))
if 1 <= target_floor <= 16 and direction in [-1, 1]:
task_queue.put((target_floor, direction))
else:
print("Invalid input")
```
这个程序模拟了两部电梯的运行,每当有新的任务时,将任务加入任务队列中,电梯线程会从任务队列中取出任务并执行。在电梯运行过程中,会输出当前所在楼层,开关门等信息。
阅读全文