1. 用函數創建多線程
在Python3中,Python提供了一個內置模塊 threading.Thread
,可以很方便地讓我們創建多線程。
threading.Thread()
一般接收兩個參數:
線程函數名:要放置線程讓其后臺執行的函數,由我們自已定義,注意不要加()
;
線程函數的參數:線程函數名所需的參數,以元組的形式傳入。若不需要參數,可以不指定。
舉個例子
import time
from threading import Thread
# 自定義線程函數。
def target(name="Python"):
for i in range(2):
print("hello", name)
time.sleep(1)
# 創建線程01,不指定參數
thread_01 = Thread(target=target)
# 啟動線程01
thread_01.start()
# 創建線程02,指定參數,注意逗號
thread_02 = Thread(target=target, args=("MING",))
# 啟動線程02
thread_02.start()
可以看到輸出
hello Python
hello MING
hello Python
hello MING
2. 用類創建多線程
相比較函數而言,使用類創建線程,會比較麻煩一點。
首先,我們要自定義一個類,對于這個類有兩點要求,
必須繼承 threading.Thread
這個父類;
必須復寫 run
方法。
這里的 run
方法,和我們上面線程函數
的性質是一樣的,可以寫我們的業務邏輯程序。在 start()
后將會調用。
來看一下例子 為了方便對比,run
函數我復用上面的main
。
import time
from threading import Thread
class MyThread(Thread):
def __init__(self, type="Python"):
# 注意:super().__init__() 必須寫
# 且最好寫在第一行
super().__init__()
self.type=type
def run(self):
for i in range(2):
print("hello", self.type)
time.sleep(1)
if __name__ == '__main__':
# 創建線程01,不指定參數
thread_01 = MyThread()
# 創建線程02,指定參數
thread_02 = MyThread("MING")
thread_01.start()
thread_02.start()
當然結果也是一樣的。
hello Python
hello MING
hello Python
hello MING
3. 線程對象的方法
上面介紹了當前 Python 中創建線程兩種主要方法。
創建線程是件很容易的事,但要想用好線程,還需要學習線程對象的幾個函數。
經過我的總結,大約常用的方法有如下這些:
# 如上所述,創建一個線程
t=Thread(target=func)
# 啟動子線程
t.start()
# 阻塞子線程,待子線程結束后,再往下執行
t.join()
# 判斷線程是否在執行狀態,在執行返回True,否則返回False
t.is_alive()
t.isAlive()
# 設置線程是否隨主線程退出而退出,默認為False
t.daemon = True
t.daemon = False
# 設置線程名
t.name = "My-Thread"
審核編輯:符乾江
-
多線程
+關注
關注
0文章
279瀏覽量
20300 -
python
+關注
關注
56文章
4823瀏覽量
86157
發布評論請先 登錄
一種實時多線程VSLAM框架vS-Graphs介紹

請問如何在Python中實現多線程與多進程的協作?
創建了用于OpenVINO?推理的自定義C++和Python代碼,從C++代碼中獲得的結果與Python代碼不同是為什么?
請問rt-thread studio如何進行多線程編譯?
socket 多線程編程實現方法
linux驅動程序的編譯方法有哪兩種
rtt工程移植后線程創建不成功怎么解決?
從多線程設計模式到對 CompletableFuture 的應用

評論