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))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容