python線程啟動(dòng)的四種方式總結(jié)
本文主要給大家介紹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)線程。
import multiprocessing
import threading
def func():
print("Hello, World!")
if __name__ == "__main__":
p = multiprocessing.Process(target=func)
p.start()
p.join()總結(jié)
到此這篇關(guān)于python線程啟動(dòng)的四種方式的文章就介紹到這了,更多相關(guān)python線程啟動(dòng)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python對(duì)Excel不同的行分別復(fù)制不同的次數(shù)
這篇文章主要介紹了如何利用Python實(shí)現(xiàn)讀取Excel表格文件數(shù)據(jù),并將其中符合我們特定要求的那一行加以復(fù)制指定的次數(shù),感興趣的小伙伴可以學(xué)習(xí)一下2023-07-07
python 用正則表達(dá)式篩選文本信息的實(shí)例
今天小編就為大家分享一篇python 用正則表達(dá)式篩選文本信息的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06
如何將Python代碼轉(zhuǎn)化為可執(zhí)行的程序
在Python中,將代碼轉(zhuǎn)成可以執(zhí)行的程序需要安裝庫(kù)pyinstaller,如果是Windows用戶,打開Anaconda?Prompt輸入相對(duì)應(yīng)代碼,下面小編給大家詳細(xì)講解如何將Python代碼轉(zhuǎn)化為可執(zhí)行的程序,感興趣的朋友一起看看吧2024-03-03
使用Keras預(yù)訓(xùn)練模型ResNet50進(jìn)行圖像分類方式
這篇文章主要介紹了使用Keras預(yù)訓(xùn)練模型ResNet50進(jìn)行圖像分類方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05

