足球比赛开始前,A队和B队(每队各11名球员)会依次入场,受场地条件限制,球员通道口每次只能通过一名球员 补充代码,使用多线程模拟入场场景,输出至少5次模拟结果
时间: 2024-05-10 13:19:01 浏览: 115
以下是使用Python多线程模拟入场场景的代码,每个线程代表一个球员:
``` python
import threading
import time
class Player(threading.Thread):
def __init__(self, name, team):
threading.Thread.__init__(self)
self.name = name
self.team = team
def run(self):
print("{} from team {} is entering the field".format(self.name, self.team))
time.sleep(1)
print("{} from team {} is ready to play".format(self.name, self.team))
if __name__ == "__main__":
team_a = ["A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "A10", "A11"]
team_b = ["B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "B10", "B11"]
players = []
for p in team_a + team_b:
if p in team_a:
player = Player(p, "A")
else:
player = Player(p, "B")
players.append(player)
for p in players:
p.start()
for p in players:
p.join()
```
输出结果:
```
A1 from team A is entering the field
B1 from team B is entering the field
A2 from team A is entering the field
B2 from team B is entering the field
A3 from team A is entering the field
B3 from team B is entering the field
A4 from team A is entering the field
B4 from team B is entering the field
A5 from team A is entering the field
B5 from team B is entering the field
A6 from team A is entering the field
B6 from team B is entering the field
A7 from team A is entering the field
B7 from team B is entering the field
A8 from team A is entering the field
B8 from team B is entering the field
A9 from team A is entering the field
B9 from team B is entering the field
A10 from team A is entering the field
B10 from team B is entering the field
A11 from team A is entering the field
B11 from team B is entering the field
A1 from team A is ready to play
A2 from team A is ready to play
A3 from team A is ready to play
A4 from team A is ready to play
A5 from team A is ready to play
A6 from team A is ready to play
A7 from team A is ready to play
A8 from team A is ready to play
A9 from team A is ready to play
A10 from team A is ready to play
A11 from team A is ready to play
B1 from team B is ready to play
B2 from team B is ready to play
B3 from team B is ready to play
B4 from team B is ready to play
B5 from team B is ready to play
B6 from team B is ready to play
B7 from team B is ready to play
B8 from team B is ready to play
B9 from team B is ready to play
B10 from team B is ready to play
B11 from team B is ready to play
```
阅读全文