• 【10.2】多线程编程-threading


    1.通过Thread类实例化

     1 #!/user/bin/env python
     2 # -*- coding:utf-8 -*-
     3 
     4 # 对于io操作来说,多线程和多进程性能差别不大
     5 # 1.通过Thread类实例化
     6 import time
     7 import threading
     8 
     9 
    10 def get_detail_html(url):
    11     print('get detail html started')
    12     time.sleep(2)
    13     print('get detail html end')
    14 
    15 
    16 def get_detail_url(url):
    17     print('get detail url started')
    18     time.sleep(2)
    19     print('get detail url end')
    20 
    21 
    22 if __name__ == '__main__':
    23     thread1 = threading.Thread(target=get_detail_html, args=('',))
    24     thread2 = threading.Thread(target=get_detail_url, args=('',))
    25 
    26     # 将thread1和thread2设置为守护线程,即主线程退出,子线程关闭
    27     thread1.setDaemon(True)
    28     thread2.setDaemon(True)
    29 
    30     start_time = time.time()
    31     # 启动线程
    32     thread1.start()
    33     thread2.start()
    34 
    35     # 阻塞,等待thread1和thread2两个子线程执行完成
    36     thread1.join()
    37     thread2.join()
    38 
    39     print('last time: {}'.format(time.time() - start_time))
    get detail html started
    get detail url started
    get detail url end
    get detail html end
    last time: 2.0038082599639893
    

    2.通过继承Thread来实现多线程

     1 #!/user/bin/env python
     2 # -*- coding:utf-8 -*-
     3 
     4 # 对于io操作来说,多线程和多进程性能差别不大
     5 # 2.通过集成Thread来实现多线程
     6 import time
     7 import threading
     8 
     9 
    10 class GetDetailHtml(threading.Thread):
    11     def __init__(self, name):
    12         super().__init__(name=name)
    13 
    14     def run(self):
    15         print('get detail html started')
    16         time.sleep(2)
    17         print('get detail html end')
    18 
    19 
    20 class GetDetailUrl(threading.Thread):
    21     def __init__(self, name):
    22         super().__init__(name=name)
    23 
    24     def run(self):
    25         print('get detail url started')
    26         time.sleep(2)
    27         print('get detail url end')
    28 
    29 
    30 if __name__ == '__main__':
    31     thread1 = GetDetailHtml('get_detail_html')
    32     thread2 = GetDetailUrl('get_detail_url')
    33 
    34     start_time = time.time()
    35 
    36     thread1.start()
    37     thread2.start()
    38 
    39     thread1.join()
    40     thread2.join()
    41     print('last time: {}'.format(time.time() - start_time))
    get detail html started
    get detail url started
    get detail html end
    get detail url end
    last time: 2.0030484199523926
    
  • 相关阅读:
    CXF调用webservice客户端
    CXF 需要的jar包下载
    跨域解决
    eclipce集成activiti
    MyEclipse 2017 CI 7安装使用
    BaiduPCS-Go的安装及使用
    织梦后台添加友链,前台不显示|修改友情链接的显示行数
    3种方法判断手机浏览器跳转WAP手机网站
    织梦DEDE后台定时分时段自动更新发布文章插件
    织梦DedeCMS信息发布员发布文章默认自动审核更新并生成HTML页面
  • 原文地址:https://www.cnblogs.com/zydeboke/p/11294647.html
Copyright © 2020-2023  润新知