threading是一個(gè)比較底層的api, 一般來說不用這個(gè)包來創(chuàng)建多線程
<h3>1.直接創(chuàng)建多線程</h3>
import time
from threading import Thread
def test():
print("------昨晚喝多了------")
time.sleep(1)
for i in range(4):
t = Thread(target = test)
t.start()
執(zhí)行結(jié)果:
------昨晚喝多了------
------昨晚喝多了------
------昨晚喝多了------
------昨晚喝多了------
<h3>2.利用thread子類創(chuàng)建多線程</h3>
可以創(chuàng)建個(gè)Thread子類,重寫run方法,再調(diào)用子類的start方法,即可開始新線程
import threading, time
class MyThread(threading.Thread):
def run(self):
for i in range(3):
time.sleep(1)
#self.name 是線程的名字
msg = "當(dāng)前線程的名字是: " + self.name + " @ " + str(i)
print(msg)
if __name__ == "__main__":
t = MyThread()
t.start()
執(zhí)行結(jié)果:
當(dāng)前線程的名字是: Thread-1 @ 0
當(dāng)前線程的名字是: Thread-1 @ 1
當(dāng)前線程的名字是: Thread-1 @ 2