Python:使用threading模塊實現多線程編程二[兩種方式起線程]

在Python中咱們主要是經過thread和threading這兩個模塊來實現的,其中Python的threading模塊是對thread作了一些包裝的,能夠更加方便的被使用,因此咱們使用threading模塊實現多線程編程。通常來講,使用線程有兩種模式,一種是建立線程要執行的函數,把這個函數傳遞進Thread對象裏,讓它來執行;另外一種是直接從Thread繼承,建立一個新的class,把線程執行的代碼放到這個新的 class裏。編程

將函數傳遞進Thread對象多線程

Python代碼app

  1. '''''
  2. Created on 2012-9-5
  3. @author:  walfred
  4. @module: thread.ThreadTest1
  5. @description:
  6. '''
  7. import threading 
  8. def thread_fun(num): 
  9. for n in range(0, int(num)): 
  10. print " I come from %s, num: %s" %( threading.currentThread().getName(), n) 
  11. def main(thread_num): 
  12.     thread_list = list(); 
  13. # 先建立線程對象
  14. for i in range(0, thread_num): 
  15.         thread_name = "thread_%s" %i 
  16.         thread_list.append(threading.Thread(target = thread_fun, name = thread_name, args = (20,))) 
  17. # 啓動全部線程  
  18. for thread in thread_list: 
  19.         thread.start() 
  20. # 主線程中等待全部子線程退出
  21. for thread in thread_list: 
  22.         thread.join() 
  23. if __name__ == "__main__": 
  24.     main(3) 

        程序啓動了3個線程,而且打印了每個線程的線程名字,這個比較簡單吧,處理重複任務就派出用場了,下面介紹使用繼承threading的方式;ide

繼承自threading.Thread類函數

Python代碼線程

  1. '''''
  2. Created on 2012-9-6
  3. @author: walfred
  4. @module: thread.ThreadTest2
  5. '''
  6. import threading 
  7. class MyThread(threading.Thread): 
  8. def __init__(self): 
  9.         threading.Thread.__init__(self); 
  10. def run(self): 
  11. print "I am %s" %self.name 
  12. if __name__ == "__main__": 
  13. for thread in range(0, 5): 
  14.         t = MyThread() 
  15.         t.start() 

        接下來的文章,將會介紹如何控制這些線程,包括子線程的退出,子線程是否存活及將子線程設置爲守護線程(Daemon)。對象

相關文章
相關標籤/搜索