python的thread模組作用

來源:互聯網
上載者:User

標籤:線程並發   封裝   time()   alt   enumerate   rom   作用   main   你好   

線程python的thread模組是比較底層的模組,python的threading模組是對thread做了一些封裝的,可以更加方便的被使用1. 使用threading模組單線程執行
import threadingimport timedef hello_for():    print("你好 世界, 你好  中國")    time.sleep(1)if __name__ == "__main__":    for i in range(5):        t = threading.Thread(target=hello_for)        t.start() #啟動線程,即讓線程開始執行

運行結果:

 

多線程執行
import threadingimport timedef hello_for():    print("你好 世界, 你好  中國")    time.sleep(1)if __name__ == "__main__":    for i in range(5):        t = threading.Thread(target=hello_for)        t.start() #啟動線程,即讓線程開始執行

運行結果:

 

說明
  1. 可以明顯看出使用了多線程並發的操作,花費時間要短很多
  2. 當調用start()時,才會真正的建立線程,並且開始執行
2. 主線程會等待所有的子線程結束後才結束
import threadingfrom time import sleep,ctimedef 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()    print(‘---結束---:%s‘%ctime())

運行結果:

3. 查看線程數量
import threadingfrom time import sleep,ctimedef 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()    while True:        length = len(threading.enumerate())        print(‘當前啟動並執行線程數為:%d‘%length)        if length<=1:            break        sleep(0.5)

運行結果:

 

python的thread模組作用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.