Python自定义线程:如何使用Python中的Thread类创建和管理线程
使用Python编写多线程应用程序可以大大提高应用程序的性能和效率。为了实现多线程功能,在Python中可以使用Thread类来创建和管理线程。Thread类是Python标准库中的一个类,它提供了一种简单、直观的方法来创建和管理线程。
创建Thread对象的方式有两种:一种是继承Thread类并重写run()方法,另一种是通过传递可调用对象(如函数)来创建Thread对象。下面分别介绍这两种方式。
- 继承Thread类并重写run()方法
这种方式需要定义一个新的类,该类继承Thread类并重写run()方法,run()方法是线程的主体,包含了线程要执行的代码。例如:
import threading
class MyThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
# 线程主体
print("Thread " + self.name + " is running")
# 创建新线程
thread1 = MyThread("1")
thread2 = MyThread("2")
# 启动线程
thread1.start()
thread2.start()
# 等待线程结束
thread1.join()
thread2.join()