python線程啟動的四種方式總結
更新時間:2024年01月06日 09:24:30 作者:天下·第二
這篇文章主要給大家介紹了關于python線程啟動的四種方式,線程可以完成一定任務,可以和其它線程共享父進程的共享變量和部分環(huán)境,相互協(xié)作來完成任務,需要的朋友可以參考下
本文主要給大家介紹python啟動線程的四種方式
1. 使用 threading 模塊
創(chuàng)建 Thread 對象,然后調用 start() 方法啟動線程。
import threading def func(): print("Hello, World!") t = threading.Thread(target=func) t.start()
2. 繼承 threading.Thread 類
重寫 run() 方法,并調用 start() 方法啟動線程。
import threading class MyThread(threading.Thread): def run(self): print("Hello, World!") t = MyThread() t.start()
3. 使用 concurrent.futures 模塊
使用ThreadPoolExecutor 類的 submit() 方法提交任務,自動創(chuàng)建線程池并執(zhí)行任務。
import concurrent.futures def func(): print("Hello, World!") with concurrent.futures.ThreadPoolExecutor() as executor: future = executor.submit(func)
4. 使用 multiprocessing 模塊的 Process 類
創(chuàng)建進程,然后在進程中啟動線程。
import multiprocessing import threading def func(): print("Hello, World!") if __name__ == "__main__": p = multiprocessing.Process(target=func) p.start() p.join()
總結
到此這篇關于python線程啟動的四種方式的文章就介紹到這了,更多相關python線程啟動內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python對Excel不同的行分別復制不同的次數(shù)
這篇文章主要介紹了如何利用Python實現(xiàn)讀取Excel表格文件數(shù)據(jù),并將其中符合我們特定要求的那一行加以復制指定的次數(shù),感興趣的小伙伴可以學習一下2023-07-07