Python中多线程通过threading模块实现,常用方式包括:1. 创建Thread实例并启动;2. 继承Thread类重写run方法;3. 使用Lock确保共享数据安全;4. 设置守护线程随主线程结束而退出。

Python 中实现多线程主要通过 threading 模块,而不是旧的 thread 模块(在 Python 3 中已被重命名为 _thread,不推荐直接使用)。threading 模块提供了更高级、更易用的接口来管理多线程任务。
最常见的方式是创建 threading.Thread 类的实例,并指定要执行的函数。
示例代码:
import threading import time <p>def print_numbers(): for i in range(5): time.sleep(1) print(i)</p><p>def print_letters(): for letter in 'abcde': time.sleep(1.5) print(letter)</p><h1>创建线程</h1><p>t1 = threading.Thread(target=print_numbers) t2 = threading.Thread(target=print_letters)</p><h1>启动线程</h1><p>t1.start() t2.start()</p><h1>等待线程结束</h1><p>t1.join() t2.join()</p>
可以自定义一个类继承 threading.Thread,并重写 run() 方法。
立即学习“Python免费学习笔记(深入)”;
class MyThread(threading.Thread):
def run(self):
print(f"{self.name} 开始")
time.sleep(2)
print(f"{self.name} 结束")
<h1>使用自定义线程</h1><p>t = MyThread()
t.start()
t.join()</p>多个线程访问共享数据时,可能引发竞争条件。可以使用 Lock 来保证同一时间只有一个线程操作数据。
lock = threading.Lock() counter = 0 <p>def increment(): global counter for _ in range(100000): lock.acquire() counter += 1 lock.release()</p><p>t1 = threading.Thread(target=increment) t2 = threading.Thread(target=increment) t1.start() t2.start() t1.join() t2.join() print(counter) # 正确输出 200000</p>
设置 daemon=True 后,主线程结束时,守护线程会自动退出。
def background_task():
while True:
print("后台运行...")
time.sleep(1)
<p>t = threading.Thread(target=background_task, daemon=True)
t.start()</p><p>time.sleep(3) # 主程序运行3秒后退出
print("主程序结束")</p><h1>程序退出时,守护线程自动终止</h1>基本上就这些。threading 模块让多线程编程变得简单,但要注意避免共享资源冲突。合理使用锁和守护线程,能写出稳定高效的并发程序。不复杂但容易忽略细节。
以上就是python thread模块如何实现多线程的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号