python下實現多線程有兩種方式:一種是通過函數的方式產生新的線程,另外一種是通過物件導向的方式實現
通過調用thread模組中的start_new_thread()函數來產生新線程
#!/usr/bin/env python#encoding:utf-8#author:zhxiaimport threadimport timethread_count=0;def test(num,interval): for x in xrange(1,10): print 'current thread is:%d,and x is:%d'%(num,x) time.sleep(interval) thread.exit_thread()if __name__=='__main__': thread.start_new_thread(test,(1,1)) thread.start_new_thread(test,(2,1)) thread.start_new_thread(test,(3,1)) #為了防止主線程在子線程之前退出,需要檢測當前的子線程數目,直到所有的子線程執行完畢 time.sleep(0.001) #必需sleep一下,否則取不到子線程的數目 while thread._count()>0: time.sleep(0.5)
通過threading模組實現:
#!/usr/bin/env python#encoding:utf-8#author:zhxiaimport timeimport threadingimport sysclass test(threading.Thread): def __init__(self,num,interval): threading.Thread.__init__(self) self.thread_num=num self.interval=interval def run(self): for x in xrange(1,9): print 'current thread is %d,and x is %d'%(self.thread_num,x) time.sleep(self.interval)if __name__=='__main__': t1=test(1,1) t2=test(2,1) t3=test(3,1) t1.start(); t2.start(); t3.start();