推荐答案
// www.javascriptcn.com code example
import threading
import time
def worker():
print(f"Worker thread started: {threading.current_thread().name}")
time.sleep(2)
print(f"Worker thread finished: {threading.current_thread().name}")
# 创建线程
thread1 = threading.Thread(target=worker)
thread2 = threading.Thread(target=worker)
# 启动线程
thread1.start()
thread2.start()
# 等待线程完成
thread1.join()
thread2.join()
print("Main thread finished")本题详细解读
多线程的概念
多线程是指在一个进程中同时运行多个线程,每个线程可以执行不同的任务。线程是操作系统能够进行运算调度的最小单位,它被包含在进程之中,是进程中的实际运作单位。Python 中的 threading 模块提供了多线程编程的支持。
多线程的用法
创建线程:使用
threading.Thread类来创建线程。target参数指定线程要执行的函数。启动线程:调用
start()方法来启动线程。线程启动后会自动调用target指定的函数。等待线程完成:使用
join()方法等待线程执行完毕。主线程会阻塞,直到调用join()的线程执行完毕。线程同步:在多线程环境中,如果多个线程需要访问共享资源,可能会引发竞争条件。可以使用
threading.Lock来确保同一时间只有一个线程访问共享资源。
示例代码解析
worker()函数是线程要执行的任务,模拟了一个耗时操作(通过time.sleep(2))。thread1和thread2是两个线程对象,它们都执行worker()函数。start()方法启动线程,线程开始执行worker()函数。join()方法确保主线程等待thread1和thread2执行完毕后再继续执行。- 最后,主线程打印 "Main thread finished",表示所有线程都已执行完毕。
注意事项
- Python 的全局解释器锁(GIL)限制了同一时间只有一个线程执行 Python 字节码,因此在 CPU 密集型任务中,多线程可能不会带来性能提升。
- 对于 I/O 密集型任务,多线程可以有效提高程序的并发性能。
- 在多线程编程中,需要注意线程安全问题,避免竞争条件和死锁。