python線程的幾種創建方式


Python3 線程中常用的兩個模塊為:

  • _thread
  • threading(推薦使用)

使用Thread類創建

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) # 屏蔽此行代碼,試試看,程序是否會立馬結束?
    print('---結束---:%s'%ctime())
"""
輸出結果:
---開始---:Sat Aug 24 08:44:21 2019
正在唱歌...0
正在跳舞...0---結束---:Sat Aug 24 08:44:21 2019
正在唱歌...1
正在跳舞...1
正在唱歌...2
正在跳舞...2
"""

說明:主線程會等待所有的子線程結束后才結束

使用Thread子類創建

為了讓每個線程的封裝性更完美,所以使用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屬性中保存的是當前線程的名字
            print(msg)


if __name__ == '__main__':
    t = MyThread()
    t.start()
"""
輸出結果:
I'm Thread-5 @ 0
I'm Thread-5 @ 1
I'm Thread-5 @ 2
"""

使用線程池ThreadPoolExecutor創建

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"]
    # 最大線程數為3,使用with可以自動關閉線程池,簡化操作
    with ThreadPoolExecutor(3) as executor:
        for each in seed: 
        	# map可以保證輸出的順序, submit輸出的順序是亂的
            executor.submit(sayhello, each)

    print("主線程結束")


if __name__ == '__main__':
    main()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM