Python中有兩個線程模塊,分別是thread和threading,threading是thread的升級版。threading的功能更強大。
創建線程有3種方法:
1、thread模塊的start_new_thread函數
2、繼承自threading.Thread模塊
3、用theading.Thread直接返回一個thread對象,然后運行它的start方法
方法一、thread模塊的start_new_thread函數
其函數原型:
start_new_thread(function,atgs[,kwargs])
其參數含義如下:
function: 在線程中執行的函數名
args:元組形式的參數列表。
kwargs: 可選參數,以字典的形式指定參數(即對一些參數進行指定初始化)
代碼:
import thread def hello(id = 0, interval = 2): for i in filter(lambda x: x % interval == 0, range(10)): print "Thread id : %d, time is %d\n" % (id, i) if __name__ == "__main__": #thread.start_new_thread(hello, (1,2)) 這種調用形式也是可用的 #thread.start_new_thread(hello, (2,4)) thread.start_new_thread(hello, (), {"id": 1}) thread.start_new_thread(hello, (), {"id": 2})
方法二:繼承自threading.Thread模塊
注意:必須重寫run函數,而且想要運行應該調用start方法
import threading class MyThread(threading.Thread): def __init__(self, id, interval): threading.Thread.__init__(self) self.id = id self.interval = interval def run(self): for x in filter(lambda x: x % self.interval == 0, range(10)): print "Thread id : %d time is %d \n" % (self.id, x) if __name__ == "__main__": t1 = MyThread(1, 2) t2 = MyThread(2, 4) t1.start() t2.start() t1.join() t2.join()
方法三:用theading.Thread直接返回一個thread對象,然后運行它的start方法
import threading def hello(id, times): for i in range(times): print "hello %s time is %d\n" % (id , i) if __name__ == "__main__": t = threading.Thread(target=hello, args=("hawk", 5)) t.start()