zoukankan      html  css  js  c++  java
  • 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))
    
     
     
  • 相关阅读:
    Vue 监听子组件事件
    延时队列
    AES加密
    centos7.9 iftop 工具源码安装
    angular pass get paragrams by router
    Android chrome console in PC
    powershell 运行带路径的exe
    win下 nrm ls报错
    windows10 安装 node 16 解决node-sass node-gyp报错
    位图和布隆过滤器
  • 原文地址:https://www.cnblogs.com/jeff-ideas/p/10540343.html
Copyright © 2011-2022 走看看