Python的标準庫提供了兩個子產品: _thread threading _thread threading _thread
和
,
是低級子產品,
是進階子產品,對
進行了封裝。絕大多數情況下,我們隻需要使用threading這個進階子產品。
方式一:把一個函數傳入并建立Thread執行個體,然後調用start()開始執行
import threading
def loop():
for i in range(30):
print(threading.current_thread().name + " --- " + str(i))
threadA = threading.Thread(target=loop, name="線程A")
threadB = threading.Thread(target=loop, name="線程B")
threadA.start()
threadB.start()
執行結果部分截圖如下:
'''
遇到問題沒人解答?小編建立了一個Python學習交流QQ群:531509025
尋找有志同道合的小夥伴,互幫互助,群裡還有不錯的視訊學習教程和PDF電子書!
'''
import threading
class MyThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
for i in range(20):
print(threading.current_thread().name + " --- " + str(i))
threadA = MyThread("線程A")
threadB = MyThread("線程B")
threadA.start()
threadB.start()