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))

你可能感兴趣的:(Python 多线程编程)