#-*-coding:utf-8-*-'''python标准库提供了两个多线程模块,分别为thread和threading,其中thread模块是低级模块,threading是高级模块,对thread进行了封装,绝大多数情况下,只需要使用threading这个高级模块'''#使用threading模块创建多线程#方式一:把一个函数传入并穿件Thread实例,然后调用start方法开始执行import randomimport time,threading#新线程执行的代码# def thread_run(urls):# print("Current %s is running...."% threading.current_thread().name)# for url in urls:# print('%s--->>>%s'%(threading.current_thread().name,url))# time.sleep(random.random())# print("%s ended." % threading.current_thread().name)# print("%s is runing..."%threading.current_thread().name)# t1=threading.Thread(target=thread_run,name='Thread_1',args=(['url_1','url_2','url_3']))# t2=threading.Thread(target=thread_run,name='Thread_1',args=(['url_4','url_5','url_6']))# t1.start()# t2.start()# t1.join()# t2.join()# print("%s ended."% threading.current_thread().name)#方式二:直接从threading.Thread集成并穿件线程类,然后重新__init__方法和run方法class myThread(threading.Thread): def __init__(self,name,urls): threading.Thread.__init__(self,name=name) self.urls=urls def run(self): print("Current %s is running..."%threading.current_thread().name) for url in self.urls: print("%s--->>>%s"%(threading.current_thread().name,url)) time.sleep(random.random())print("%s is running..."%threading.current_thread().name)t1=myThread(name='Thread 1',urls=['url_1','url_2','url_3'])t2=myThread(name='Thread 2',urls=['url_4','url_5','url_6'])t1.start()t2.start()t1.join()t2.join()print("%s ended "% threading.current_thread().name)
摘自《Python爬虫开发与项目实战》