温馨提示×

python怎么创建线程

小亿
116
2023-08-15 11:11:00
栏目: 编程语言

Python中创建线程的方法有两种,一种是使用threading模块,另一种是继承Thread类。

使用threading模块创建线程的步骤如下:

  1. 导入threading模块:import threading

  2. 创建一个线程对象:t = threading.Thread(target=函数名, args=(参数1, 参数2, ...))

  3. 启动线程:t.start()

示例代码:

import threading
# 定义一个函数,作为线程执行的目标函数
def func(arg):
print("线程执行中,参数为:", arg)
# 创建一个线程对象,并传递目标函数和参数
t = threading.Thread(target=func, args=("Hello",))
# 启动线程
t.start()

继承Thread类创建线程的步骤如下:

  1. 导入threading模块:import threading

  2. 定义一个继承自Thread类的子类,并重写run()方法,在run()方法中实现线程的具体逻辑。

  3. 创建子类的对象,并调用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类的方式更加灵活,可以更好地利用面向对象的特性进行线程的管理和控制。

0