python 子线程休眠,主线程继续执行
时间: 2024-10-09 12:07:21 浏览: 50
在Python中,如果你想要在一个子线程中暂停一段时间(休眠),而让主线程继续执行,你可以使用`threading`模块中的`Thread`类以及`time.sleep()`函数。下面是一个简单的例子:
```python
import threading
import time
# 定义子线程函数
def worker_thread():
print(f"Worker thread started at {time.ctime()}")
# 这里休眠5秒
time.sleep(5)
print(f"Worker thread finished at {time.ctime()}")
# 主线程函数
def main_thread():
print("Main thread started")
# 创建子线程
t = threading.Thread(target=worker_thread)
t.start() # 启动子线程
# 子线程休眠期间,主线程会继续执行
time.sleep(2) # 主线程在这里等待2秒
print("Main thread continues after a short pause")
t.join() # 等待子线程完成
if __name__ == "__main__":
main_thread()
```
在这个示例中,`worker_thread`会在启动后休眠5秒,而`main_thread`在此期间不会停止,它会继续执行`time.sleep(2)`这部分。当子线程结束休眠后,主线程通过`t.join()`来等待子线程结束。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)