在Python中实现多线程可以通过以下两种主要方法:
1. 使用`threading`模块:
创建线程对象,通过`threading.Thread`类,并传入目标函数和参数。
调用线程对象的`start()`方法启动线程。
可以使用`join()`方法等待线程结束。
示例代码:
```python
import threading
def print_numbers():
for i in range(10):
print("Thread 1:", i)
def print_letters():
for letter in 'abcdefghij':
print("Thread 2:", letter)
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
thread1.start()
thread2.start()

thread1.join()
thread2.join()
print("Main thread exiting.")
2. 使用`_thread`模块(较低级):调用`_thread.start_new_thread()`函数来创建新线程。函数需要传入要执行的函数和参数(以元组形式)。示例代码:```pythonimport _thread
import time
def job():
print("这是一个需要执行的任务。")
print("当前线程的个数:", threading.active_count())
print("当前线程的信息:", threading.current_thread())
time.sleep(100)
if __name__ == "__main__":
_thread.start_new_thread(job, ())
_thread.start_new_thread(job, ())
job()
请注意,`_thread`模块在Python 3.x中已经不推荐使用,并在Python 3.10中被移除。建议使用`threading`模块进行多线程编程。
另外,Python的多线程受全局解释器锁(GIL)的限制,这意味着即使在多核处理器上,也无法实现真正的并行执行。如果需要并行计算,可以考虑使用`multiprocessing`模块。
