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