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 尋找list中最大元素對應(yīng)的索引方法
今天小編就為大家分享一篇python 尋找list中最大元素對應(yīng)的索引方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06
簡單談?wù)凱ython面向?qū)ο蟮南嚓P(guān)知識
由于馬上就要期末考試了,正在抓緊時間復(fù)習(xí) 所以這一篇就拖了很久,抱歉啦~ 今天會說說: 屬性私有,方法私有,重寫,魔術(shù)方法,需要的朋友可以參考下2021-01-01
python?管理系統(tǒng)實(shí)現(xiàn)mysql交互的示例代碼
這篇文章主要介紹了python?管理系統(tǒng)實(shí)現(xiàn)mysql交互,本文通過實(shí)例代碼圖文相結(jié)合給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-12-12
教你怎么用python實(shí)現(xiàn)字符串轉(zhuǎn)日期
今天教各位小伙伴怎么用python實(shí)現(xiàn)字符串轉(zhuǎn)日期,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)python的小伙伴很有幫助,需要的朋友可以參考下2021-05-05

