python線程的幾種創(chuàng)建方式詳解
Python3 線程中常用的兩個模塊為:
- _thread
- threading(推薦使用)
使用Thread類創(chuàng)建
import threading
from time import sleep,ctime
def sing():
for i in range(3):
print("正在唱歌...%d"%i)
sleep(1)
def dance():
for i in range(3):
print("正在跳舞...%d"%i)
sleep(1)
if __name__ == '__main__':
print('---開始---:%s'%ctime())
t1 = threading.Thread(target=sing)
t2 = threading.Thread(target=dance)
t1.start()
t2.start()
#sleep(5) # 屏蔽此行代碼,試試看,程序是否會立馬結(jié)束?
print('---結(jié)束---:%s'%ctime())
"""
輸出結(jié)果:
---開始---:Sat Aug 24 08:44:21 2019
正在唱歌...0
正在跳舞...0---結(jié)束---:Sat Aug 24 08:44:21 2019
正在唱歌...1
正在跳舞...1
正在唱歌...2
正在跳舞...2
"""
說明:主線程會等待所有的子線程結(jié)束后才結(jié)束
使用Thread子類創(chuàng)建
為了讓每個線程的封裝性更完美,所以使用threading模塊時,往往會定義一個新的子類class,只要繼承threading.Thread就可以了,然后重寫run方法。
import threading
import time
class MyThread(threading.Thread):
def run(self):
for i in range(3):
time.sleep(1)
msg = "I'm "+self.name+' @ '+str(i) #name屬性中保存的是當(dāng)前線程的名字
print(msg)
if __name__ == '__main__':
t = MyThread()
t.start()
"""
輸出結(jié)果:
I'm Thread-5 @ 0
I'm Thread-5 @ 1
I'm Thread-5 @ 2
"""
使用線程池ThreadPoolExecutor創(chuàng)建
from concurrent.futures import ThreadPoolExecutor
import time
import os
def sayhello(a):
for i in range(10):
time.sleep(1)
print("hello: " + a)
def main():
seed = ["a", "b", "c"]
# 最大線程數(shù)為3,使用with可以自動關(guān)閉線程池,簡化操作
with ThreadPoolExecutor(3) as executor:
for each in seed:
# map可以保證輸出的順序, submit輸出的順序是亂的
executor.submit(sayhello, each)
print("主線程結(jié)束")
if __name__ == '__main__':
main()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用Python進(jìn)行同期群分析(Cohort?Analysis)
同期群(Cohort)的字面意思(有共同特點或舉止類同的)一群人,比如不同性別,不同年齡。這篇文章主要介紹了用Python語言來進(jìn)行同期群分析,感興趣的同學(xué)可以閱讀參考一下本文2023-03-03
Python中Sorted()函數(shù)的key參數(shù)使用方法詳解
這篇文章主要介紹了關(guān)于Python中Sorted()函數(shù)的key參數(shù)使用方法 ,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-06-06
提高Python生產(chǎn)力的五個Jupyter notebook插件
Jupyter Notebook 因其可用性和實用性而成為數(shù)據(jù)分析和機器學(xué)習(xí)模型領(lǐng)域最流行的 IDE,它也是很多數(shù)據(jù)初學(xué)者的首選 IDE。它最具特色的是,擁有豐富的插件、擴展數(shù)據(jù)處理能力和提升工作效率2021-11-11
解決matplotlib.pyplot在Jupyter notebook中不顯示圖像問題
這篇文章主要介紹了解決matplotlib.pyplot在Jupyter notebook中不顯示圖像問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Python實現(xiàn)隨機劃分圖片數(shù)據(jù)集的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何通過Python實現(xiàn)隨機將圖片與標(biāo)注文件劃分為訓(xùn)練集和測試集,文中的示例代碼簡潔易懂,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-05-05

