使用场景:代码量比较小的场景。
#!/usr/bin/python3 # -*- coding: utf-8 -*- import threading import time def test_thread(num): print(num) time.sleep(2) if __name__ =="__main__": thread1 = threading.Thread(target=test_thread,args=('我是一只猫',)) #target=需要执行的函数名 args=传参,必须带括号和逗号 start_time = time.time() #获取当前时间 #thread1.setDaemon(True) #守护线程 同步主线程退出就退出子线程 thread1.start() #启动线程 thread1.join() #阻塞线程,子线程完成之后才能退出,否则不允许主线程退出 print("线程耗时:{}".format(start_time-time.time()))
第二种多线程使用方法
通过继承Thread类来执行多线程,不适用线程池。适合线程少点复杂逻辑结构程序
class Deatile(threading.Thread): def __init__(self,name): super().__init__(name=name) def run(self): #重载run方法执行多线程类 print('heihgen{}'.format(self.name)) if __name__ =="__main__": thread1 = Deatile('我是一个变量') start_time = time.time() #获取当前时间 #thread1.setDaemon(True) #守护线程 同步主线程退出就退出子线程 thread1.start() #启动线程 thread1.join() #阻塞线程,子线程完成之后才能退出,否则不允许主线程退出 print("线程耗时:{}".format(start_time-time.time()))