今天開(kāi)始準(zhǔn)備學(xué)習(xí)threading這個(gè)庫(kù)啦已慢,畢竟面試的時(shí)候少不了問(wèn)多進(jìn)程逾礁,多線程的睹栖,所以還是要準(zhǔn)備準(zhǔn)備的硫惕,嘻嘻。
今天理解最基本的線程運(yùn)行和join的使用
我就直接貼代碼了,跑下代碼野来,看下注釋就明白了恼除。
import threading
import time
def music(func):
for i in range(2):
sleep_seconds = 4
print(f"Begin listen to {func, time.ctime()}")
time.sleep(sleep_seconds)
print(f"過(guò)了{(lán)sleep_seconds}s")
print(f"end listening at the music: {func, time.ctime()} ")
def movie(func):
for i in range(2):
sleep_seconds = 5
print(f"begin watching at the{func, time.ctime()} ")
time.sleep(sleep_seconds)
print(f'過(guò)了{(lán)sleep_seconds}s')
print(f"end watching at the movie: {func, time.ctime()}")
if __name__ == '__main__':
threads = []
t1 = threading.Thread(target=music, args=['七里香', ])
t2 = threading.Thread(target=movie, args=['阿甘正傳', ])
threads.append(t1)
threads.append(t2)
print("對(duì)于join的理解,三個(gè)小例子")
"""
第一種情況
"""
# print("下面是三個(gè)小例子曼氛,方便理解")
# print("第一種:循環(huán)中按順序執(zhí)行豁辉,啟動(dòng)music線程,然后阻塞舀患,然后啟動(dòng)movie線程徽级,在阻塞,最后在結(jié)束主進(jìn)程")
# for t in threads:
# t.start()
# t.join()
# print(f"all over {time.ctime()}")
# print("最終結(jié)果就是,必須等到music放完了才會(huì)看moive,然后回到主進(jìn)程")
"""
第二種
"""
# print("第二種: 循環(huán)中啟動(dòng)兩個(gè)線程聊浅,然后阻塞music線程,意思是必須等music線程結(jié)束后才會(huì)執(zhí)行主進(jìn)程餐抢。")
# print("你可以看到當(dāng)music執(zhí)行完成后现使,all over被打印了出來(lái)")
# for t in threads:
# t.start()
# t1.join()
# print(f"all over {time.ctime()}")
"""
第三種
"""
print("第三種:跟第二種一樣,阻塞movie進(jìn)程,必須等到movie放完了,才會(huì)執(zhí)行主進(jìn)程")
for t in threads:
t.start()
t2.join()
print(f"all over {time.ctime()}")
發(fā)現(xiàn)不錯(cuò)的文章
明天
- 理解python中的全局解釋鎖旷痕。
- 測(cè)測(cè)python中io密集型和計(jì)算機(jī)密集型多線程的差異碳锈。