之前爬虫用到过多线程,好久不用了,来复习一下
使用的是pthon3自带的threading模块
使用threading.Thread类创建线程
import time
import threading
def test_thread(para='test', sleep=1):
"""线程运行函数"""
time.sleep(sleep)
print(para)
def main():
#通过实例化threading.Thread类创建线程
thread_test = threading.Thread(target=test_thread, args=('test',))
thread_test1 = threading.Thread(target=test_thread, args=('test1',4))
# start()启动线程
thread_test.start()
thread_test1.start()
print('线程运行结束')
if __name__ == '__main__':
main()
join()方法的使用
创建一个线程时,看不出来效果
import threading, time
def test_thread(para='test'):
"""线程运行函数"""
print(para)
def run(data_list):
thread_list = []
for i in data_list:
thread_list.append(threading.Thread(target=test_thread(i)))
for i in thread_list:
i.start()
print('start waiting: ' + time.strftime('%H:%M:%S') + "\n")
for i in thread_list:
i.join()
print('join waiting: ' + time.strftime('%H:%M:%S') + "\n")
print('线程结束')
if __name__ == '__main__':
run([1,2,3,4,5,6])
创建两个线程时
import threading, time
def test_thread(para='test', sleep=3):
"""线程运行函数"""
print('start:'+ para + ' ' + time.strftime('%H:%M:%S') + "\n" )
time.sleep(sleep)
def run():
test_list = []
test1 = threading.Thread(target = test_thread('test1', 3))
test1.start()
test_list.append(test1)
test2 = threading.Thread(target = test_thread('test2', 8))
test2.start()
test_list.append(test2)
print('start join: ' + time.strftime('%H:%M:%S') + "\n")
for item in test_list:
item.join()
print('end join: ' + time.strftime('%H:%M:%S') + "\n")
if __name__ == '__main__':
run()
# 分析 两个线程同时执行join(), 当test1执行完后,test2才开始执行, join()退出
# thread.join()的作用是
# 阻塞主进程,专注于执行多线程中的程序,多线程多join的情况下,依次执行各线程的join方法,前头一个结束了才能执行后面一个。