Python中创建线程的方法有两种,一种是使用threading
模块,另一种是继承Thread
类。
使用threading
模块创建线程的步骤如下:
-
导入
threading
模块:import threading
-
创建一个线程对象:
t = threading.Thread(target=函数名, args=(参数1, 参数2, ...))
-
启动线程:
t.start()
示例代码:
import threading # 定义一个函数,作为线程执行的目标函数 def func(arg): print("线程执行中,参数为:", arg) # 创建一个线程对象,并传递目标函数和参数 t = threading.Thread(target=func, args=("Hello",)) # 启动线程 t.start()
继承Thread
类创建线程的步骤如下:
-
导入
threading
模块:import threading
-
定义一个继承自
Thread
类的子类,并重写run()
方法,在run()
方法中实现线程的具体逻辑。 -
创建子类的对象,并调用
start()
方法启动线程。
示例代码:
import threading # 定义一个继承自Thread类的子类 class MyThread(threading.Thread): def __init__(self, arg): threading.Thread.__init__(self) self.arg = arg def run(self): print("线程执行中,参数为:", self.arg) # 创建子类的对象,并调用start()方法启动线程 t = MyThread("Hello") t.start()
以上两种方法都可以用来创建线程,但是继承Thread
类的方式更加灵活,可以更好地利用面向对象的特性进行线程的管理和控制。