登录
首页 >  文章 >  python教程

Pythonthread模块多线程教程

时间:2025-11-16 20:37:35 166浏览 收藏

想要提升Python程序的运行效率?多线程技术是关键!本文详细介绍了如何使用Python的`threading`模块实现多线程,摆脱旧的`thread`模块的束缚。我们将深入探讨创建`Thread`实例、继承`Thread`类重写`run`方法这两种常用的线程创建方式,并提供清晰的代码示例,助你快速上手。同时,文章还讲解了如何利用`Lock`锁确保共享数据的安全性,避免多线程并发时的资源冲突。此外,你还将了解到守护线程的妙用,让你的线程随主线程一同优雅地结束。掌握这些技巧,让你的Python程序更上一层楼!

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

python thread模块如何实现多线程

Python 中实现多线程主要通过 threading 模块,而不是旧的 thread 模块(在 Python 3 中已被重命名为 _thread,不推荐直接使用)。threading 模块提供了更高级、更易用的接口来管理多线程任务。

1. 使用 threading.Thread 创建线程

最常见的方式是创建 threading.Thread 类的实例,并指定要执行的函数。

  • target:指定线程要运行的函数
  • args:传递给函数的参数,以元组形式传入
  • start():启动线程
  • join():等待线程执行完成

示例代码:

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>

2. 继承 threading.Thread 类

可以自定义一个类继承 threading.Thread,并重写 run() 方法。

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>

3. 线程同步与共享数据安全

多个线程访问共享数据时,可能引发竞争条件。可以使用 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>

4. 守护线程(Daemon Thread)

设置 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 模块让多线程编程变得简单,但要注意避免共享资源冲突。合理使用锁和守护线程,能写出稳定高效的并发程序。不复杂但容易忽略细节。

今天带大家了解了的相关知识,希望对你有所帮助;关于文章的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>