python线程示例
时间: 2024-02-29 17:49:54 浏览: 31
当然可以!以下是一个简单的Python线程示例:
```python
import threading
# 定义一个线程函数
def print_numbers():
for i in range(1, 6):
print(i)
# 创建一个线程对象
thread = threading.Thread(target=print_numbers)
# 启动线程
thread.start()
# 主线程继续执行其他任务
for i in range(6, 11):
print(i)
# 等待线程执行完毕
thread.join()
# 线程执行完毕后,主线程继续执行
print("All done!")
```
在这个示例中,我们首先定义了一个名为`print_numbers`的线程函数,它会打印数字1到5。然后,我们使用`threading.Thread`类创建了一个线程对象,并将`print_numbers`函数作为目标函数传递给它。接着,我们调用线程对象的`start`方法来启动线程。
在主线程中,我们打印数字6到10。然后,我们调用线程对象的`join`方法,使主线程等待线程执行完毕。最后,当线程执行完毕后,主线程继续执行并打印"All done!"。
这个示例展示了如何使用Python的`threading`模块创建和启动线程,并且演示了主线程和子线程的并发执行。
相关问题
python 多线程 示例
Python多线程示例程序可以使用Python内置的threading模块或者PyQt5中的QThread类来实现。其中,使用threading模块可以通过创建Thread对象并将函数传递给target参数来实现多线程。而使用QThread类则需要继承该类并重写run()方法,在该方法中实现线程需要执行的内容。下面是两个示例代码:
使用threading模块:
```
import threading
import time
def print_numbers():
for i in range(5):
print(i)
time.sleep(0.5)
def print_letters():
for letter in ['a', 'b', 'c', 'd', 'e']:
print(letter)
time.sleep(0.5)
t1 = threading.Thread(target=print_numbers)
t2 = threading.Thread(target=print_letters)
t1.start()
t2.start()
t1.join()
t2.join()
print('All threads finished')
```
使用QThread类:
```
from PyQt5.QtCore import QThread
import time
class MyThread(QThread):
def __init__(self, parent=None):
super(MyThread, self).__init__(parent)
def run(self):
for i in range(5):
print(i)
time.sleep(0.5)
thread = MyThread()
thread.start()
thread.wait()
print('Thread finished')
```
python多线程示例
下面是一个简单的 Python 多线程示例:
```python
import threading
def worker(num):
"""线程要执行的任务"""
print(f"Worker {num} started")
# TODO: 线程要执行的任务
print(f"Worker {num} finished")
if __name__ == '__main__':
# 创建10个线程
threads = []
for i in range(10):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
# 等待所有线程完成
for t in threads:
t.join()
print("All threads finished")
```
在这个示例中,我们创建了一个 `worker` 函数,它是每个线程要执行的任务。我们创建了10个线程,并启动它们。`join()` 方法用于等待所有线程完成。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)