本文主要給大家介紹python啟動(dòng)線程的四種方式
1. 使用 threading 模塊
創(chuàng)建 Thread 對(duì)象,然后調(diào)用 start() 方法啟動(dòng)線程。
import threading
def func():
print("Hello, World!")
t = threading.Thread(target=func)
t.start()
2. 繼承 threading.Thread 類
重寫 run() 方法,并調(diào)用 start() 方法啟動(dòng)線程。
import threading
class MyThread(threading.Thread):
def run(self):
print("Hello, World!")
t = MyThread()
t.start()
3. 使用 concurrent.futures 模塊
使用ThreadPoolExecutor 類的 submit() 方法提交任務(wù),自動(dòng)創(chuàng)建線程池并執(zhí)行任務(wù)。
import concurrent.futures
def func():
print("Hello, World!")
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(func)
4. 使用 multiprocessing 模塊的 Process 類
創(chuàng)建進(jìn)程,然后在進(jìn)程中啟動(dòng)線程。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-650864.html
import multiprocessing
import threading
def func():
print("Hello, World!")
if __name__ == "__main__":
p = multiprocessing.Process(target=func)
p.start()
p.join()
以上就是python中啟動(dòng)線程的幾種方式的介紹,希望對(duì)你有所幫助。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-650864.html
到了這里,關(guān)于python - 線程的啟動(dòng)的幾種方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!