Python中Thread 类使用说明

在Python中,threading.Thread 类是用于创建和管理线程的核心类。下面通过实例来说明如何使用 threading.Thread:

  • 通过直接实例化Thread类并传入target函数
import threading
import time

# 定义一个将在新线程中运行的函数
def my_function(name):
    for _ in range(5):
        print(f"线程 {name} 正在运行")
        time.sleep(1)  # 模拟IO操作或其他耗时任务

# 创建两个线程
thread1 = threading.Thread(target=my_function, args=("Thread-1",))
thread2 = threading.Thread(target=my_function, args=("Thread-2",))

# 启动两个线程
thread1.start()
thread2.start()

# 确保主线程等待所有子线程完成
thread1.join()
thread2.join()

print("所有线程都已完成")
  • 通过继承Thread类并重写run()方法:
import threading
import time

class MyThread(threading.Thread):
    def __init__(self, name):
        super().__init__()
        self.name = name

    def run(self):
        for _ in range(5):
            print(f"自定义线程 {self.name} 正在运行")
            time.sleep(1)

# 创建并启动自定义线程
thread1 = MyThread("CustomThread-1")
thread2 = MyThread("CustomThread-2")

thread1.start()
thread2.start()

# 等待所有线程结束
thread1.join()
thread2.join()

print("所有自定义线程都已完成")

以上两个示例展示了两种创建和使用线程的方法,它们都能实现多线程执行任务。然而,在实际应用中,需要注意由于全局解释器锁(GIL)的存在,Python的多线程并不能充分利用多核CPU的优势进行计算密集型任务的并行处理,但对于IO密集型任务或频繁切换的任务来说,多线程仍然可以提升程序性能。同时,在多线程环境下,需要考虑线程安全问题,可能需要使用线程同步机制如锁(Lock)、条件变量(Condition)、信号量(Semaphore)等来保护共享资源的访问。

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

semicolon_helloword

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值