python3多線程編程

# 對於io操做來講,多線程和多進程性能差異不大


import time
from threading import Thread


# 1. 經過Thread類實例化
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")


# thread1 = Thread(target=get_detail_html, args=("",))
# thread2 = Thread(target=get_detail_url, args=("",))
# # thread1.setDaemon(True)     # 設置爲守護線程,當主線程退出的時候,子線程kill掉
# # thread2.setDaemon(True)
# start_time = time.time()
# thread1.start()
# thread2.start()
# thread1.join()
# thread2.join()
# print(F"last time: {time.time() - start_time}")


# -------------------------------------------------------------------------

# 2. 經過繼承Thread來實現多線程
class GetDetailHtml(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 GetDetailUrl(Thread):
    def __init__(self, name):
        super().__init__(name=name)

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


thread1 = GetDetailHtml("get_detail_html")
thread2 = GetDetailUrl("get_detail_url")
start_time = time.time()
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print(F"last time: {time.time() - start_time}")

# -------------------------------------------------------------------------

if __name__ == '__main__':
    pass
相關文章
相關標籤/搜索