Python通过继承实现多线程

本套课在线学习视频(网盘地址,保存到网盘即可免费观看):

​https://pan.quark.cn/s/677661ea63b3​

本节将介绍如何利用Python中的thread模块和threading模块实现多线程,并通过继承threading.Thread类并重写run方法的方式创建自定义线程类。我们将以创建唱歌和跳舞两个线程类为例,详细讲解如何实现多线程程序。

00:00 - 通过继承实现多线程

创建自定义线程类

我们将创建两个自定义线程类:SingThread和DanceThread。这两个类分别实现了线程启动、延迟和结束时的自定义行为,并通过传递参数来控制延迟时间。

import threading
import time

# 创建唱歌线程类
class SingThread(threading.Thread):
    def __init__(self, delay):
        super().__init__()
        self.delay = delay
    
    def run(self):
        for _ in range(5):
            print("Singing...")
            time.sleep(self.delay)

# 创建跳舞线程类
class DanceThread(threading.Thread):
    def __init__(self, delay):
        super().__init__()
        self.delay = delay
    
    def run(self):
        for _ in range(5):
            print("Dancing...")
            time.sleep(self.delay)

# 创建并启动线程
sing_thread = SingThread(1)
dance_thread = DanceThread(1.5)

sing_thread.start()
dance_thread.start()

sing_thread.join()
dance_thread.join()

print("All threads have finished")

03:53 - Python编程:实现多线程

创建多个线程实例

在主程序中,通过for循环创建了多个线程实例,并启动这些线程。为了确保主线程能够等待所有子线程完成后再继续执行,将所有线程放入一个任务列表中,并使用for循环调用每个线程的join方法。

import threading
import time

# 创建唱歌线程类
class SingThread(threading.Thread):
    def __init__(self, name, delay):
        super().__init__()
        self.name = name
        self.delay = delay
    
    def run(self):
        print(f"Thread {self.name} started")
        for _ in range(3):
            print(f"{self.name} is singing...")
            time.sleep(self.delay)
        print(f"Thread {self.name} completed")

# 创建跳舞线程类
class DanceThread(threading.Thread):
    def __init__(self, name, delay):
        super().__init__()
        self.name = name
        self.delay = delay
    
    def run(self):
        print(f"Thread {self.name} started")
        for _ in range(3):
            print(f"{self.name} is dancing...")
            time.sleep(self.delay)
        print(f"Thread {self.name} completed")

# 创建并启动多个线程
threads = []
for i in range(3):
    sing_thread = SingThread(f"SingThread-{i}", 1 + i * 0.5)
    dance_thread = DanceThread(f"DanceThread-{i}", 1 + i * 0.3)
    
    threads.append(sing_thread)
    threads.append(dance_thread)
    
    sing_thread.start()
    dance_thread.start()

# 等待所有线程完成
for thread in threads:
    thread.join()

print("All threads have finished")

计算程序的总运行时间

通过计算程序的开始时间和结束时间的差值,可以得到整个程序的运行时间。

import threading
import time

# 创建唱歌线程类
class SingThread(threading.Thread):
    def __init__(self, name, delay):
        super().__init__()
        self.name = name
        self.delay = delay
    
    def run(self):
        print(f"Thread {self.name} started")
        for _ in range(3):
            print(f"{self.name} is singing...")
            time.sleep(self.delay)
        print(f"Thread {self.name} completed")

# 创建跳舞线程类
class DanceThread(threading.Thread):
    def __init__(self, name, delay):
        super().__init__()
        self.name = name
        self.delay = delay
    
    def run(self):
        print(f"Thread {self.name} started")
        for _ in range(3):
            print(f"{self.name} is dancing...")
            time.sleep(self.delay)
        print(f"Thread {self.name} completed")

# 记录开始时间
start_time = time.time()

# 创建并启动多个线程
threads = []
for i in range(3):
    sing_thread = SingThread(f"SingThread-{i}", 1 + i * 0.5)
    dance_thread = DanceThread(f"DanceThread-{i}", 1 + i * 0.3)
    
    threads.append(sing_thread)
    threads.append(dance_thread)
    
    sing_thread.start()
    dance_thread.start()

# 等待所有线程完成
for thread in threads:
    thread.join()

# 记录结束时间并计算总运行时间
end_time = time.time()
total_time = end_time - start_time
print(f"All threads have finished. Total time: {total_time:.2f} seconds")

通过这些示例代码,您可以更好地理解如何在Python中使用threading模块创建和管理多线程程序,并通过继承threading.Thread类来实现自定义线程类。同时,您还可以学习如何计算程序的总运行时间,以评估多线程程序的性能。

相关推荐

  1. Python通过继承实现线

    2024-07-12 20:26:01       20 阅读
  2. Python线使用实践

    2024-07-12 20:26:01       53 阅读
  3. python线

    2024-07-12 20:26:01       38 阅读
  4. python 线

    2024-07-12 20:26:01       26 阅读
  5. 线实例

    2024-07-12 20:26:01       25 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 20:26:01       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 20:26:01       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 20:26:01       58 阅读
  4. Python语言-面向对象

    2024-07-12 20:26:01       69 阅读

热门阅读

  1. 2024年C#优秀实用的类库推荐

    2024-07-12 20:26:01       25 阅读
  2. L1 Simple_ReAct_Agent

    2024-07-12 20:26:01       20 阅读
  3. rust way step 7

    2024-07-12 20:26:01       20 阅读
  4. sqlalchemy通过查询参数生成query

    2024-07-12 20:26:01       18 阅读
  5. git reset hard和soft的使用和区别

    2024-07-12 20:26:01       20 阅读
  6. 目前分布式光纤测温系统的主流架构有哪些?

    2024-07-12 20:26:01       20 阅读
  7. docker pull 报错:missing signature key,docker版本问题

    2024-07-12 20:26:01       18 阅读
  8. 第六篇:Python元组:不可变序列的魅力

    2024-07-12 20:26:01       19 阅读