python 多线程 示例
时间: 2024-04-01 17:29:47 浏览: 78
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')
```
阅读全文