3. 假设图书馆现有图书100本,请你打开两个线程,分别是借图书(每间隔1秒借1次)和还图书(每间隔3秒还1次),模拟借书还书过程,结果类似如下所示:
时间: 2023-09-12 09:12:04 浏览: 42
以下是使用Python多线程模拟借书还书过程的代码:
```python
import threading
import time
# 定义图书馆总数为100
total_books = 100
# 定义借书线程函数
def borrow_books():
global total_books
while True:
# 模拟借书过程,每次借1本,间隔1秒
time.sleep(1)
total_books -= 1
print("借书成功,当前图书馆总数为:", total_books)
# 定义还书线程函数
def return_books():
global total_books
while True:
# 模拟还书过程,每次还1本,间隔3秒
time.sleep(3)
total_books += 1
print("还书成功,当前图书馆总数为:", total_books)
# 创建借书线程和还书线程,并启动线程
borrow_thread = threading.Thread(target=borrow_books)
return_thread = threading.Thread(target=return_books)
borrow_thread.start()
return_thread.start()
```
运行以上代码,可以看到借书和还书交替进行,并且图书馆总数不会小于0或大于100。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)