在Python中实现多线程可以通过以下两种主要方法:
使用`threading`模块
创建`Thread`对象,将目标函数作为参数传入。
调用`start()`方法启动线程。
使用`join()`方法等待线程结束。
示例代码:
```python
import threading
def print_numbers():
for i in range(10):
print(i)
def print_letters():
for letter in 'abcdefghij':
print(letter)
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
继承`Thread`类
定义一个新的类,继承自`Thread`。
重写`run()`方法,定义线程要执行的任务。
实例化这个类并调用`start()`方法启动线程。
示例代码:
```python
import threading
class MyThread(threading.Thread):
def run(self):
for i in range(10):
print(i)
thread = MyThread()
thread.start()
thread.join()
需要注意的是,Python的全局解释器锁(GIL)限制了多线程在CPU密集型任务中的性能,因此多线程更适合I/O密集型任务。
另外,Python还提供了`concurrent.futures.ThreadPoolExecutor`类,可以更方便地管理线程池。