Bootstrap

python多线程调用类方法_python多线程两种调用方式

直接调用

Thread类定义:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

Thread 的构造方法中,最重要的参数是 target,所以我们需要将一个 callable 对象赋值给它,线程才能正常运行。

如果要让一个 Thread 对象启动,调用它的 start() 方法就好了。

1 import threading

2 import time

3

4 def sayhi(num): #定义每个线程要运行的函数

6 print("running on number:%s" %num)

8 time.sleep(3)

9

10 if __name__ == '__main__':

12 t1 = threading.Thread(target=sayhi,args=(1,)) #生成一个线程实例

13 t2 = threading.Thread(target=sayhi,args=(2,)) #生成另一个线程实例

15 t1.start() #启动线程

16 t2.start() #启动另一个线程

18 print(t1.getName()) #获取线程名

19 print(t2.getName())

继承式调用

自定义一个 Thread 的子类,然后复写它的 run() 方法。

import threading

import time

class MyThread(threading.Thread):

def __init__(self,num):

threading.Thread.__init__(self)

self.num = num

def run(self):#定义每个线程要运行的函数

print("running on number:%s" %self.num)

time.sleep(3)

if __name__ == '__main__':

t1 = MyThread(1)

t2 = MyThread(2)

t1.start()

t2.start()

Thread 的生命周期

1、 创建对象时,代表 Thread 内部被初始化。

2、 调用 start() 方法后,thread 会开始运行。

3、 thread 代码正常运行结束或者是遇到异常,线程会终止。

;