一个简单的Python多线程
首先对一段普通的代码进行测试
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import time def RunThreading(n): print("Running %s Threading"%n) time.sleep(3) RunThreading("First") RunThreading("Second")
运行脚本
首先打印Running First Threading,然后间隔3秒打印Running Second Threading,最后间隔3秒结束
等待时间为6s
接下来测试多线程的脚本进行对比
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import threading import time def RunThreading(n): print("Running" ,n, "Threading") time.sleep(3) t1 = threading.Thread(target=RunThreading, args=("First",))#即使只有一个参数也要加逗号 t2 = threading.Thread(target=RunThreading, args=("Second",)) t1.start() t2.start()
运行脚本
同时打印出Running First Threading和Running Second Threading,脚本没有立即结束,而是间隔了三秒之后才结束
t1和t2是同时进行的,所以等待的时间只有3s
用类方法来调用多线程
#-*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import threading class MyThread(threading.Thread): def __init__(self,n): super(MyThread,self).__init__() self.n = n def run(self): #必须是run print ("Running %s Threading"%self.n) t1 = MyThread("First") t2 = MyThread("Second") t1.start() t2.start()
运行结果