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