多线程实现科学家就餐
时间: 2023-11-17 19:56:08 浏览: 34
为了实现科学家就餐的多线程程序,我们可以采用以下步骤:
1. 定义一个餐厅类,其中包含一个菜单和一个就餐方法。
2. 定义一个科学家类,其中包含一个选择菜品的方法和一个就餐的方法。
3. 在主函数中创建多个科学家对象,并启动它们的就餐线程。
具体实现细节如下:
1. 餐厅类:
```python
import threading
class Restaurant:
def __init__(self):
self.menu = ['糖醋排骨', '宫保鸡丁', '红烧肉', '清蒸鲈鱼']
self.lock = threading.Lock()
def dining(self, name, food):
with self.lock:
print('{} 正在享用 {}.'.format(name, food))
```
2. 科学家类:
```python
import threading
import random
class Scientist:
def __init__(self, name, restaurant):
self.name = name
self.restaurant = restaurant
def choose_food(self):
return random.choice(self.restaurant.menu)
def eat(self):
food = self.choose_food()
self.restaurant.dining(self.name, food)
```
3. 主函数:
```python
if __name__ == '__main__':
restaurant = Restaurant()
scientists = [Scientist('科学家{}'.format(i), restaurant) for i in range(10)]
threads = [threading.Thread(target=s.eat) for s in scientists]
for t in threads:
t.start()
for t in threads:
t.join()
```