對于python 多線程的理解,摸索了一天半 令我真的頭禿
from time import sleep,ctime
import logging
import threading # 首先導(dǎo)入threading 模塊,這是使用多線程的前提洲尊。
logging.basicConfig(level=logging.INFO)
loops = [2,4]
def loop(nloop,nsec):
logging.info("start loop"+str(nloop)+ctime())
sleep(nsec)
logging.info("end loop"+str(nloop) + ctime())
def main():
logging.info("start all at" + ctime())
thread = []
nloops = range(len(loops))
for i in nloops:
t = threading.Thread(target=loop,args=(i,loops[i]))
thread.append(t)
"""
這里第一個循環(huán)的意思
創(chuàng)建了thread數(shù)組间坐,創(chuàng)建線程t,使用threading.Thread()方法养距,
在這個方法中調(diào)用loop方法target=loop和二,args方法對loop方法進(jìn)行傳參贫母。 把創(chuàng)建好的線程t裝到threads數(shù)組中幅虑。
start nloop0 nloop1 一起運(yùn)行
nloop0 間隔2s nloop1 間隔了4秒
"""
for i in nloops:
thread[i].start() # 開始2個線程活動丰滑。
for i in nloops:
thread[i].join() # 用于等待線程終止。join()的作用是,在子線程完成運(yùn)行之前褒墨,這個子線程的父線程將一直被阻塞炫刷。
logging.info("end all at " + ctime())
if __name__ == '__main__':
main()
第二個示例
from time import sleep, ctime
import threading
def music(name):
for i in range(2):
print("I listen now", name, ctime())
sleep(3)
def move(name):
for i in range(2):
print("I listen now", name, ctime())
sleep(2)
threds = []
t1 = threading.Thread(target=music, args=("鳳凰傳奇",))
threds.append(t1)
t2 = threading.Thread(target=move, args=("阿凡達(dá)",))
threds.append(t2)
if __name__ == '__main__':
print("The main process starts", ctime())
for i in threds:
i.setDaemon(True)
i.start()
i.join()
print("The main process ends", ctime())