用 python写三台电梯协同
时间: 2024-06-15 08:02:04 浏览: 140
在 Python 中编写多线程或协程来模拟三台电梯的协同工作是一个有趣的应用,可以使用 threading 模块或者 asyncio 库来实现并发控制。这里我将提供一个简单的示例,展示如何使用线程来模拟电梯状态和响应请求:
```python
import threading
from time import sleep
class Elevator:
def __init__(self, id, capacity, current_floor=0):
self.id = id
self.capacity = capacity
self.current_floor = current_floor
self.lock = threading.Lock()
def request(self, floor):
with self.lock:
if self.current_floor == floor:
print(f"Elevator {self.id} is already at floor {floor}")
return
elif self.current_floor < floor:
self.move_towards(floor)
else:
self.move_downward(floor)
def move_towards(self, target_floor):
print(f"Elevator {self.id} moving up to {target_floor}...")
sleep(2) # 假设电梯每秒移动一层
self.current_floor += 1
print(f"Elevator {self.id} arrived at floor {self.current_floor}")
def move_downward(self, target_floor):
print(f"Elevator {self.id} moving down to {target_floor}...")
sleep(2) # 假设电梯每秒移动一层
self.current_floor -= 1
print(f"Elevator {self.id} arrived at floor {self.current_floor}")
# 创建三台电梯
elevator_1 = Elevator(1, 4)
elevator_2 = Elevator(2, 4)
elevator_3 = Elevator(3, 4)
# 用户请求
threads = [
threading.Thread(target=elevator_1.request, args=(4,)),
threading.Thread(target=elevator_2.request, args=(10,)),
threading.Thread(target=elevator_3.request, args=(7,))
]
# 启动所有线程
for thread in threads:
thread.start()
# 等待所有线程完成
for thread in threads:
thread.join()
```
在这个示例中,我们创建了三个 `Elevator` 类的实例,并为每个电梯定义了请求、向上移动和向下移动的方法。当有用户请求时,电梯会相应地移动。
阅读全文