#-*-coding:utf-8-*- '''python標準庫提供了兩個多線程模塊,分別爲thread和threading, 其中thread模塊是低級模塊,threading是高級模塊,對thread進行了封裝, 絕大多數狀況下,只須要使用threading這個高級模塊''' #使用threading模塊建立多線程 #方式一:把一個函數傳入並穿件Thread實例,而後調用start方法開始執行 import random import 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爬蟲開發與項目實戰》python