Python 多線程編程

  1. 通過實例化Thread類
import threading
import time


def get_detail_html(url):
    print("get detail html started")
    time.sleep(2)
    print("get detail html end")


def get_detail_url(url):
    print("get detail url started")
    time.sleep(4)
    print("get detail url end")


if __name__ == "__main__":
    thread1 = threading.Thread(target=get_detail_html, args=("",))
    thread2 = threading.Thread(target=get_detail_url, args=("",))

    # thread1.setDaemon(True) # 設置爲守護線程,意思是主線程關閉後,也關閉這個守護線程
    thread2.setDaemon(True)
    start_time = time.time()
    thread1.start()
    thread2.start()

    thread1.join()  #
    thread2.join()  # 等待這兩個線程執行完成後,再執行主線程
    print("last time: {}".format(time.time()-start_time))
  1. 通過繼承Thread
import threading
import time

class GetDetalHTML(threading.Thread):
    def __init__(self, name):
        super().__init__(name=name)

    def run(self):
        print("get detail html started")
        time.sleep(2)
        print("get detail html end")


class GetDetalURL(threading.Thread):
    def __init__(self, name):
        super().__init__(name=name)

    def run(self):
        print("get detail url started")
        time.sleep(4)
        print("get detail url end")


if __name__ == "__main__":
    thread1 = GetDetalHTML("get_detail_html")
    thread2 = GetDetalURL("get_detail_url")

    start_time = time.time()
    thread1.start()
    thread2.start()

    thread1.join()  #
    thread2.join()  # 等待這兩個線程執行完成後,再執行主線程
    print("last time: {}".format(time.time() - start_time))
發佈了67 篇原創文章 · 獲贊 6 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章